java按指定编码写入和读取文件内容的类分享
可以指定编码如:utf-8来写入和读取文件。如果文件编码未知,可以通过该方法先得到文件的编码后再指定正确的编码来读取,否则会出现文件乱码问题。
如何识别文件编码请参考:
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));
}
}