一、Java讀取文件
案例1:讀取D盤的1.txt文件
編碼:
1 File file = new File("D:/1.txt"); 2 FileReader fr = new FileReader(file); 3 BufferedReader bf = new BufferedReader(fr); 4 StringBuffer sbuffer = new StringBuffer(); 5 String temp = null; 6 while((temp = bf.readLine()) !=null){ 7 sbuffer.append(temp+"\n"); 8 } 9 System.out.println(sbuffer.toString()); 10 11 System.out.println();
結果:
二、寫入文件
案例:講D盤中的1.txt文件內容寫入D盤一個2.txt文件。
編碼:
1 File file = new File("D:/1.txt"); 2 FileReader fr = new FileReader(file); 3 BufferedReader bf = new BufferedReader(fr); 4 StringBuffer sbuffer = new StringBuffer(); 5 String temp = null; 6 while((temp = bf.readLine()) !=null){ 7 sbuffer.append(temp+"\n"); 8 } 9 System.out.println(sbuffer.toString()); 10 11 System.out.println(); 12 File outfile = new File("D:/2.txt"); 13 if(!outfile.exists()){ 14 try { 15 outfile.createNewFile(); 16 } catch (IOException e) { 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 } 20 } 21 byte[] b = (sbuffer.toString()).getBytes(); 22 FileOutputStream fs = null; 23 fs = new FileOutputStream(outfile); 24 fs.write(b); 25 26 fs.close(); 27 bf.close(); 28