随手写的Java向文本文件写字符串的类

  今天看了一篇讲Java IO流的文章,好长时间没用IO流了,回顾了一下Java编写IO程序的思路,之前文章中有介绍。对于写二进制文件我们习惯用 面向字节类的流。对于写字符我们使用面向字符类的流。但是我们明白在计算机底层,数据是以字节进行存储的。面向字符流只是为了方便我们程序员对文本文件的处理,因为在我们平常写程序中处理最多的数据类型也就是文本。这些面向字符流,是对面向字节的封装,把细节封装起来。

  我们向Text文件中写入一段 字符串 比如 "中国人",首先 要对其进行编码,计算机只懂 ASCII,ASCII中又没有包含 '中' '国' '人'这三个字符,所以要选择合适的编码方案如(GBK/UTF-8)将"中国人"转换为 ASCII字节数组。当我们打开Text文件的时候notepad这个程序按照 指定的编码方案 将 ACII字节数组 进行组合,显示正确的字符串。所以当我们打开文本文件的时候,就会显示"中国人"。

复制代码
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class MyStringWriter {
    private OutputStream out;
    private Charset encoding;
    private String lineSeparator;

    public MyStringWriter(String file) throws FileNotFoundException {
        this(file, System.getProperty("file.encoding"));// 获取操作系统默认编码
    }

    public MyStringWriter(String file, String encoding)
            throws FileNotFoundException {
        this(new FileOutputStream(file), encoding);
    }

    public MyStringWriter(OutputStream out, String encoding) {
        this.out = out;
        this.encoding = Charset.forName(encoding);
        this.lineSeparator = System.getProperty("line.separator");// 获取操作系统的行分割符
    }

    public void write(String str) throws IOException {
        out.write(encoding.encode(str).array());//向文件中写入编码后的字节数组
    }

    public void writeLine(String line) throws IOException {
        write(line);
        for (int i = 0; i < lineSeparator.toCharArray().length; i++) {
            out.write(lineSeparator.toCharArray()[i]);
        }
    }

    public void close() throws IOException {
        out.close();
    }

    public static void main(String[] args) throws IOException {
        MyStringWriter writer = new MyStringWriter("F:\\demo.txt");
        writer.write("大家好!");
        writer.writeLine("我是中国人");
        writer.writeLine("我喜欢编程");
        writer.close();
    }
}
复制代码

 

  

posted on   Arts&Crafts  阅读(446)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示