字符流与字节流区别为基本数据单位不同,字节流一次获取一个字节 (8 byte), 字符流一次获取一个字符(1 char =2 byte),字符流常用语处理文本文件。

字符流常用子类 FileReaderFileWriter; 字符流核心是处理编码转换,避免中文等特殊字符乱码。

1 字符输入流

1.1 FileReader

默认编码规则 winGBKlinuxutf-8容易乱码,不推荐直接用

1.1.1 示例代码

public static void main(String[] args) {  
    File file = new File("F:\\allFile\\01 temp\\1.txt");  
    try (FileReader fileReader = new FileReader(file)) {  
        int charChar;//读取字符  
        while ((charChar = fileReader.read()) != -1) {  
            System.out.print((char) charChar);//打印读取的字符  
        }  
    } catch (IOException e) {  
        throw new RuntimeException(e);  
    }  
}

1.2 InputStreamReader

字符转换输入流,将字节流转换为字符流,可以指定编码。

1.2.1 代码实例

public static void main(String[] args) {  
    File file = new File("F:\\allFile\\01 temp\\1.txt");  
    try (FileInputStream inputStream = new FileInputStream(file);  
         InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);){  
        char[] buffer = new char[1024];  
        int bytesRead;  
        while ((bytesRead = inputStreamReader.read(buffer)) != -1) {  
            System.out.print(new String(buffer, 0, bytesRead));  
        }  
    } catch (IOException e) {  
        throw new RuntimeException(e);  
    }  
}

1.3 FileWrite

1.3.1 示例代码

public static void main(String[] args) {  
    File file = new File("F:\\allFile\\01 temp\\1.txt");  
    try (FileWriter fileWriter = new FileWriter(file)) {  
        String str = "hello world";  
        fileWriter.write(str);  
    } catch (IOException e) {  
        throw new RuntimeException(e);  
    }  
}

1.4 OutputStreamWriter

1.4.1 示例代码

public static void main(String[] args) {  
    File file = new File("F:\\allFile\\01 temp\\1.txt");  
    try {  
        FileOutputStream outputStream = new FileOutputStream(file);  
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);  
        outputStreamWriter.write("hello world12312312");  
        outputStreamWriter.close();  
    }catch (Exception e){  
        e.printStackTrace();  
    }  
}