下边的例子展示了从文件读入字符流到内存, 然后再加上行号后逐行输出到新的文件. 在文件输出流包装中使用了FileWriter->BufferedWriter->PrintWriter, 使用BufferedWriter是基于性能考虑, 使用缓冲来提升IO性能, PrintWriter是为了格式化输出, 它提供和PrintStream相同的方法, 可以提供平台无关的字符输出. 此外, 在输出结束后需要调用close关闭输出流, 这样可以清空缓冲区, 否则可能会输出不完整.
package com.cnsuning.file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
public class BasicFileOutput {
public BasicFileOutput() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bReader = new BufferedReader(new StringReader(BufferInputFile.read("D:\\work\\会员账户管理\\sales_svn.txt")));
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("D:\\test.txt")));
String line;
int lineNum = 1;
while (null != (line = bReader.readLine())) {
out.print(lineNum+": "+line+"\n");
lineNum++;
}
out.close();
System.out.print(BufferInputFile.read("D:\\test.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
此外, PrintWriter提供多种构造函数重载, 可以更便捷地创建, 下边就是一个用文件名直接创建的示例:
package com.cnsuning.file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
public class BasicFileOutput {
public BasicFileOutput() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bReader = new BufferedReader(new StringReader(BufferInputFile.read("D:\\work\\会员账户管理\\sales_svn.txt")));
try {
PrintWriter out = new PrintWriter("D:\\test.txt");
String line;
int lineNum = 1;
while (null != (line = bReader.readLine())) {
out.print(lineNum+": "+line+"\n");
lineNum++;
}
out.close();
System.out.print(BufferInputFile.read("D:\\test.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}