zoukankan      html  css  js  c++  java
  • 随手写的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();
        }
    }

      

  • 相关阅读:
    DAI widget和stream widget建立连接
    asoc驱动注册
    snd_card设备
    DAPM event机制
    Linux下gprof和oprofiling性能测试工具
    [KERNEL OOM] debug linux out of memory的一些技巧
    [kernel]kernel启动时,如何在driver中获取uboot的bootargs
    [HOW TO USE HW BRP] 如何使用ARM hardware self debug tools monitor 内存寄存器被踩问题。
    【Kernel ftrace】使用kernel ftrace追踪IRQ的例子
    [panic] 一个kernel panic错误分析的例子
  • 原文地址:https://www.cnblogs.com/ArtsCrafts/p/MyStringWrite.html
Copyright © 2011-2022 走看看