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();
        }
    }

      

  • 相关阅读:
    Code First 数据迁移 转
    WebAPI Post接收数据
    hbase1.2.4 API改动
    spark中RDD持久化浅析
    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attr_id' in 'where clause'
    宝塔忘记面板地址怎么办? 可以找到没问题的
    卸载Apache 删除已经停止的服务
    Composer 卸载
    TP5.1模型 增删改查
    打印数据库int类型的时间戳
  • 原文地址:https://www.cnblogs.com/ArtsCrafts/p/MyStringWrite.html
Copyright © 2011-2022 走看看