Java讀取txt檔案和寫入txt檔案,java讀取txt寫入

來源:互聯網
上載者:User

Java讀取txt檔案和寫入txt檔案,java讀取txt寫入

  1. package edu.thu.keyword.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStreamReader;  
  5. import java.io.BufferedReader;  
  6. import java.io.BufferedWriter;  
  7. import java.io.FileInputStream;  
  8. import java.io.FileWriter;  
  9.   
  10. public class cin_txt {  
  11.     static void main(String args[]) {  
  12.         try { // 防止檔案建立或讀取失敗,用catch捕捉錯誤並列印,也可以throw  
  13.   
  14.             /* 讀入TXT檔案 */  
  15.             String pathname = "D:\\twitter\\13_9_6\\dataset\\en\\input.txt"; // 絕對路徑或相對路徑都可以,這裡是絕對路徑,寫入檔案時示範相對路徑  
  16.             File filename = new File(pathname); // 要讀取以上路徑的input。txt檔案  
  17.             InputStreamReader reader = new InputStreamReader(  
  18.                     new FileInputStream(filename)); // 建立一個輸入資料流對象reader  
  19.             BufferedReader br = new BufferedReader(reader); // 建立一個對象,它把檔案內容轉成電腦能讀懂的語言  
  20.             String line = "";  
  21.             line = br.readLine();  
  22.             while (line != null) {  
  23.                 line = br.readLine(); // 一次讀入一行資料  
  24.             }  
  25.   
  26.             /* 寫入Txt檔案 */  
  27.             File writename = new File(".\\result\\en\\output.txt"); // 相對路徑,如果沒有則要建立一個新的output。txt檔案  
  28.             writename.createNewFile(); // 建立新檔案  
  29.             BufferedWriter out = new BufferedWriter(new FileWriter(writename));  
  30.             out.write("我會寫入檔案啦\r\n"); // \r\n即為換行  
  31.             out.flush(); // 把緩衝區內容壓入檔案  
  32.             out.close(); // 最後記得關閉檔案  
  33.   
  34.         } catch (Exception e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.     }  
  38. }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.