可以指定编码如:utf-8来写入和读取文件。如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题。
如何识别文件编码请参考:java自动根据文件内容的编码来读取避免乱码
public class ReadWriteFileWithEncode {
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));
File file = newFile("D:\\FACE_LIST\\TOSMIS_FACE_ALL_LIST.txt");//读取文件内容到List中
List<String> ls =read(file.getPath(), "UTF-8");
for (String line : ls) {
String[] cols =StringUtils.splitPreserveAllTokens(line,Constants.SUF_PAD);
System.out.println("解析数据:"+cols[0]);
}
}
/*把数据写入到文件File中*/
public static void write(String path, String content, Stringencoding) 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();
}
/*从文件File中读取数据到字符串里*/
public static List<String> read(String path,String encoding) throws IOException {
List<String> ls = newLinkedList<String>();
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) {
ls.add(line+"\n");
}
reader.close();
return ls;
}
/*根据组织好的字符串String生成,指定格式'UTF-8'文件*/
public static void genFile(StringfileName, StringBuffer content) throws IOException {
File file = new File(fileName);
// 文件夹是否存在,不存在则创建
String path =StringUtils.substringBeforeLast(fileName, "\\");
File dir = new File(path);
if (!dir.exists()) {
org.apache.commons.io.FileUtils.forceMkdir(dir);
}
if (!file.exists()) {
file.createNewFile();
}
org.apache.commons.io.FileUtils.writeStringToFile(file,content.toString(), "UTF-8");
content = null;
}
}