java中提供一行一行读取的类是 BufferedReader,其有一个readLine()方法。
java中提供一行一行写入的类是 BufferedWriter,其有一个write方法。
【读取文件】
public void readLineFile(String filename){
try {
FileInputStream in = new FileInputStream(filename);
InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
BufferedReader bufReader = new BufferedReader(inReader);
String line = null;
int i = 1;
while((line = bufReader.readLine()) != null){
System.out.println("第" + i + "行:" + line);
i++;
}
bufReader.close();
inReader.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("读取" + filename + "出错!");
}
}
【写入文件】
public void writeLineFile(String filename, String[] content){
try {
FileOutputStream out = new FileOutputStream(filename);
OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");
BufferedWriter bufWrite = new BufferedWriter(outWriter);
for (int i = 0; i < content.length; i++) {
bufWrite.write(content[i] + "\r\n");
}
bufWrite.close();
outWriter.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("读取" + filename + "出错!");
}
}