java按指定编码写入和读取文件内容的类分享
时间:2023-06-18 10:13:01
可以指定编码如: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));
}
}