0
点赞
收藏
分享

微信扫一扫

字符流——Java

小编 2022-01-20 阅读 41

字符流

编码解码

字符串中的编码解码问题

在这里插入图片描述

中文在GBK编码中,两个字节,在UTF-8编码中,3个字节,因此,字节流读取中文会出现乱码。但是进行拷贝等操作没有问题。

读和写建议使用字符流,文件之间的拷贝使用字节流和缓冲流。

写数据

FileWriter(File file)
FileWriter(String path)


void write(int c) 写一个字符
void write(char[] chuf) 写一个字符数组
void write(char[] cbuf,int off,int len) 写一个字符数组的一部分
void write(String str) 写一个字符串
void write(String str,int off,int len) 写一个字符串的一部分。

步骤:

创建字符输出流对象
    如果文件不存在,则自动创建。但是要保证父级目录存在。
写数据
    写int类型,是在写码表上的数据。
    字符串原样写出。
    
释放资源
    
private static void demo02() throws IOException {
    FileWriter writer = new FileWriter("E:\\a.txt");
    writer.write("HEllo world");
    writer.close();

}

flush

刷新流。

测试:向一个文件中不停写 a-z,并使用tail -f查看该文件的变化。

private static void demo03() throws IOException {
    FileWriter writer = new FileWriter("/a.txt");
    int number = 97;
    int n = 0;
    while (n < 10000) {
        if (number == 122) {
            number = 97;
        }
        writer.write(number);
        writer.write("\\n");
        number++;
        n++;
        writer.flush();
    }
    writer.close();
}

读数据

FileReader(File file)
FileReader(String path)

read()
read(char[] arr)

    private static void demo04() throws IOException {
//        字符流读取
        FileReader reader = new FileReader("a.txt");
        char[] arr = new char[1024];
        int len;
        while ((len = reader.read(arr)) != -1) {
            System.out.println(new String(arr, 0, len));
        }
    }

字符缓冲流

用法和字节缓冲流类似。

BufferedWriter

BufferedReader

在这里插入图片描述

举报

相关推荐

0 条评论