更多 Java IO & NIO方面的文章拍摇,請參見文集《Java IO & NIO》
FileReader & FileWriter
讀寫格式:按字符讀寫胰挑,每次讀寫一個字符,或者讀寫一個字符數(shù)組。
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
讀寫格式:按字符讀寫寺酪,每次讀寫一個字符谓娃,或者讀寫一個字符數(shù)組脚乡,或者讀寫一個字符串 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();
}