Talk is cheap, show you the code.
一、 读文件
/**
* 读取文本文件
* 在文件编码与系统默认编码相同时,可使用FileReader,这里我们使用FileInputStream方便我们指定编码
* @param filename 文件名
* @param charset 文件编码
* @return 文件内容
* @throws IOException
*/
public static String readFile(String filename, String charset) throws IOException {
File file = new File(filename);
if (!file.exists() || file.isDirectory()) {
throw new FileNotFoundException(String.format("文件%s不存在", filename));
}
try (FileInputStream inputStream = new FileInputStream(file)) {
byte[] bytes = new byte[1024];
StringBuilder builder = new StringBuilder();
while (inputStream.read(bytes) > 0) {
builder.append(new String(bytes, charset));
}
return builder.toString();
}
}
二、写文件
/**
* 将指定内容写入文件
* @param filename 文件名
* @param content 即将写入文件的内容
* @param charset 字符编码
* @return
* @throws IOException
*/
public static boolean writeFile(String filename, String content, String charset) throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(filename)) {
byte[] bytes = content.getBytes(charset);
for (Byte b : bytes) {
outputStream.write(b);
}
}
return true;
}
三、完整代码
import java.io.*;
public class FileTest {
/**
* 读取文本文件
* @param filename 文件名
* @param charset 文件编码
* @return 文件内容
* @throws IOException
*/
public static String readFile(String filename, String charset) throws IOException {
File file = new File(filename);
if (!file.exists() || file.isDirectory()) {
throw new FileNotFoundException(String.format("文件%s不存在", filename));
}
try (FileInputStream inputStream = new FileInputStream(file)) {
byte[] bytes = new byte[1024];
StringBuilder builder = new StringBuilder();
while (inputStream.read(bytes) > 0) {
builder.append(new String(bytes, charset));
}
return builder.toString();
}
}
/**
* 将指定内容写入文件
* @param filename 文件名
* @param content 即将写入文件的内容
* @param charset 字符编码
* @return
* @throws IOException
*/
public static boolean writeFile(String filename, String content, String charset) throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(filename)) {
byte[] bytes = content.getBytes(charset);
for (Byte b : bytes) {
outputStream.write(b);
}
}
return true;
}
public static void main(String[] args) throws IOException {
String content = "锄禾日当午,汗滴禾下土。谁知盘中餐,粒粒皆辛苦。";
System.out.println(String.format("写入文件:%s", writeFile("out.txt", content, "UTF-8")));
content = readFile("out.txt", "UTF-8");
System.out.println(content);
// 测试文件编码转换
System.out.println(writeFile("out.txt", content, "GBK"));
}
}