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

      

  • 相关阅读:
    Mysql定时器定时删除表数据
    Mysql中文排序规则
    Swoole学习-Swoole入门指南
    Cygwin安装swoole及错误解决
    php://input ,$_POST, $_GET和$HTTP_RAW_POST_DATA
    tp5-微信消息接收和处理
    [软件工程] 千帆竞发图的制作
    [构建之法论坛] 助教之路
    VS社区版 使用 OpenCover 获取测试代码覆盖率
    支持多编程语言的自动测试系统
  • 原文地址:https://www.cnblogs.com/ArtsCrafts/p/MyStringWrite.html
Copyright © 2011-2022 走看看