Java以UTF-8格式读写及追加写文件示例
Posted <・)))><<
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java以UTF-8格式读写及追加写文件示例相关的知识,希望对你有一定的参考价值。
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class FileHelper {
public static void readFile(File file) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
public static void writeFile(File file, String content) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(content);
osw.flush();
}
public static void appendFile(File file, String content) throws IOException {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(file, true), // true to append
"UTF-8"
);
out.write(content);
out.close();
}
// main for test
public static void main(String[] args) throws IOException {
File file = new File("D:\test.txt");
writeFile(file, "");
appendFile(file, "你好");
appendFile(file, "!!!");
readFile(file);
}
}
以上是关于Java以UTF-8格式读写及追加写文件示例的主要内容,如果未能解决你的问题,请参考以下文章
python 文件读写模式r,r+,w,w+,a,a+的区别(附代码示例)
java 将编码格式为utf-8的文件内容以 GBK编码存到txt文档