BufferedReader 讀取文件內容,原樣輸出
阿新 • • 發佈:2017-08-11
nec ati java buffered system har 運行 寫入 讀取文件
1.新建目標類:
package com.xuzhiwen.io; public class TargetFile { public static void main(String[] args) { System.out.println("TargetFile.java"); } }
2.測試類:
package com.xuzhiwen.io; import java.io.BufferedReader; import java.io.FileReader; public class TestBufferedReader { publicstatic void main(String[] args) throws Exception { String filepath = "src/com/xuzhiwen/io/TargetFile.java"; BufferedReader read = new BufferedReader(new FileReader(filepath)); String s; StringBuffer sb = new StringBuffer(); while((s=read.readLine()) != null){ sb.append(s+"\n"); } read.close(); System.out.println(sb); } }
3.輸出結果為:
4.文件結構樹:
5. 將結果用StringReader再讀一次:
package com.xuzhiwen.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.StringReader; public class TestBufferedReader { public static voidmain(String[] args) throws Exception { String filepath = "src/com/xuzhiwen/io/TargetFile.java"; BufferedReader read = new BufferedReader(new FileReader(filepath)); String s; StringBuffer sb = new StringBuffer(); while((s=read.readLine()) != null){ sb.append(s+"\n"); } read.close(); System.out.println(sb); StringReader sr = new StringReader(sb.toString()); int c; while((c=sr.read()) != -1){ System.out.print((char)c); } } }
6. 運行結果如下:
7. 將內容寫入文件:
package com.xuzhiwen.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.StringReader; public class TestBufferedReader { public static void main(String[] args) throws Exception { String filepath = "src/com/xuzhiwen/io/TargetFile.java"; BufferedReader read = new BufferedReader(new FileReader(filepath)); String s; StringBuffer sb = new StringBuffer(); while((s=read.readLine()) != null){ sb.append(s+"\n"); } read.close(); System.out.println(sb); System.out.println("=============================================="); StringReader sr = new StringReader(sb.toString()); int c; while((c=sr.read()) != -1){ System.out.print((char)c); } sr.close(); System.out.println("=============================================="); String file = "basic.out"; BufferedReader br = new BufferedReader(new StringReader(sb.toString())); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); int lineCount = 1; String ss; while((ss=br.readLine()) != null){ pw.println(lineCount+": "+ss); lineCount++; } pw.close(); } }
8. 運行結果:
9. 打開: basic.out文件:
BufferedReader 讀取文件內容,原樣輸出