对于一些大文件,如果处理不谨慎,JAVA很容易出现OutofMemary错误,这又是一个很大的题目,
一般讲,我们使用BufferedWriter,BufferedReader来处理,交给API读写,这样一定程度上可以避免这种错误。
但是,汉字,日文等等,特定编码的话,这个BufferedWriter,BufferedReader,初始化要么是流,要么是文件没法指定编码。
因为,支持流,所以其实曲线是可以的,贴代码。
InputStreamReader isw;
isw = new InputStreamReader(new FileInputStream("c:\\demo.txt"),
Charset.forName("UTF-8"));
bufReader = new BufferedReader(isw);
OutputStreamWriter osw;
osw = new OutputStreamWriter(new FileOutputStream("c:\\demo.txt"),
Charset.forName("UTF-8"));
bufWriter = new BufferedWriter(osw);
全套读写代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
public class DemoFileWriter {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("HI1");
try {
writer();
System.out.println("HI2");
reader();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("HI3");
}
public static void writer() throws IOException {
BufferedWriter bufWriter = null;
try {
OutputStreamWriter osw;
osw = new OutputStreamWriter(new FileOutputStream("c:\\demo.txt"),
Charset.forName("UTF-8"));
// FileOutputStream("c:\\demo.txt"),"UTF-8"));
bufWriter = new BufferedWriter(osw);
int intCount = 0;
while (true) {
intCount++;
if (intCount > 1000)
break;
bufWriter.write("日本語テスト,日本語テスト,日本語テスト,日本語テスト,日本語テスト,日本語テスト");
bufWriter.write("\r\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (bufWriter != null)
bufWriter.close();
}
}
public static void reader() throws IOException {
BufferedReader bufReader = null;
try {
InputStreamReader isw;
isw = new InputStreamReader(new FileInputStream("c:\\demo.txt"),
Charset.forName("UTF-8"));
bufReader = new BufferedReader(isw);
String data;
while ((data = bufReader.readLine()) != null) {
System.out.println(data);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (bufReader != null)
bufReader.close();
}
}
}