可以指定編碼如:utf-8來寫入和讀取文件。如果文件編碼未知,可以通過該方法先得到文件的編碼後再指定正確的編碼來讀取,否則會出現文件亂碼問題。
如何識別文件編碼請參考:java自動根據文件內容的編碼來讀取避免亂碼
代碼如下:
package com.zuidaima.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
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 ReadWriteFileWithEncode {
public static void write(String path, String content, String encoding)
throws IOException {
File file = new File(path);
file.delete();
file.createNewFile();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), encoding));
writer.write(content);
writer.close();
}
public static String read(String path, String encoding) throws IOException {
String content = "";
File file = new File(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), encoding));
String line = null;
while ((line = reader.readLine()) != null) {
content += line + "\n";
}
reader.close();
return content;
}
public static void main(String[] args) throws IOException {
String content = "中文內容";
String path = "c:/test.txt";
String encoding = "utf-8";
ReadWriteFileWithEncode.write(path, content, encoding);
System.out.println(ReadWriteFileWithEncode.read(path, encoding));
}
}