character stream
encode decode
Encoding and decoding problems in strings
Chinese is two bytes in GBK encoding, and three bytes in UTF-8 encoding. Therefore, garbled characters will appear when reading Chinese from the byte stream. But there is no problem in performing operations such as copying.
It is recommended to use character streams for reading and writing, and byte streams and buffer streams for copying between files.
write data
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) 写一个字符串的一部分。
step:
创建字符输出流对象
如果文件不存在,则自动创建。但是要保证父级目录存在。
写数据
写int类型,是在写码表上的数据。
字符串原样写出。
释放资源
private static void demo02() throws IOException {
FileWriter writer = new FileWriter("E:\\a.txt");
writer.write("HEllo world");
writer.close();
}
flush
Refresh the stream.
Test: Write az to a file continuously, and use tail -f to view the changes of the file.
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();
}
read data
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));
}
}
character buffer stream
Usage is similar to byte buffer stream.
BufferedWriter
BufferedReader