更多 Java IO & NIO方面的文章,请参见文集《Java IO & NIO》
FileReader & FileWriter
读写格式:按字符读写,每次读写一个字符,或者读写一个字符数组。
public static void main(String[] args) throws Exception {
FileReader fread = new FileReader("a.txt");
FileWriter fwriter = new FileWriter("b.txt");
int c;
while ((c = fread.read()) != -1) {
System.out.print((char) c);
fwriter.write(c);
}
fwriter.flush();
}
使用缓冲流 BufferedReader & BufferedWriter
读写格式:按字符读写,每次读写一个字符,或者读写一个字符数组,或者读写一个字符串 String。
public static void main(String[] args) throws Exception {
BufferedReader breader = new BufferedReader(new FileReader("a.txt"));
BufferedWriter bwriter = new BufferedWriter(new FileWriter("b.txt"));
String s;
while ((s = breader.readLine()) != null) {
System.out.print(s);
bwriter.write(s);
}
bwriter.flush();
}
PrintWriter
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter(System.out);
pw.println("Hello World");
pw.flush();
}