写出中文
向txt文件中写出中文,通过下面代码的演示,因为一个中文占2个字节,所以按照字节写出中文时会出现乱码的情况。
package com.monkey1024.stream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 向txt文件中写入中文
*
*/
public class WordWrite {
public static void main(String[] args) {
try (FileOutputStream fis = new FileOutputStream("word.txt");) {
String msg = "好好学习";
//bos.write(msg.getBytes());
//每次写出3个字节,因为一个中文占用2个字节,所以导致乱码
fis.write(msg.getBytes(), 0, 3);
//换行
fis.write("\r\n".getBytes());
fis.write("天天向上".getBytes());
fis.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取中文
从txt文件中读取文件,下面代码也出现了乱码问题
package com.monkey1024.stream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 从txt文件中读取中文
*
*/
public class WordRead {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("word.txt");) {
byte[] arr = new byte[3];
int temp;
while ((temp = fis.read(arr)) != -1) {
System.out.println(new String(arr, 0, temp));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
要想解决乱码的问题,可以使用字符流Reader和Writer