java 文字檔讀寫

來源:互聯網
上載者:User
  一、從一個檔案到另一個檔案的讀寫

public static void main(String[] args)...{

        try...{
           File rFile = new File("E:/test/text1.txt");
           File wFile = new File("E:/test/text2.txt"); 
           BufferedReader br = new BufferedReader(new FileReader(rFile));
           BufferedWriter bw = new BufferedWriter(new FileWriter(wFile,true));/*此處如果是false,則從檔案頭 寫起,也就說text2.txt原有的內容回被覆蓋掉*/
          
           String tempStr = br.readLine();
       
           while(tempStr!=null)
           ...{
              // bw.write(tempStr);
               bw.append(tempStr);
               bw.newLine();
               bw.flush();
               tempStr = br.readLine();
               
           }
           bw.close();//這個先關掉
           br.close();
        }catch(Exception e)...{
            System.out.println(e.getMessage());
        }
    }

 

 

二、擷取從鍵盤輸入的字元,寫到檔案中

 

 try ...{
            BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in)); 
            System.out.print("Enter a line:");
            String strIn = stdin.readLine();
            System.out.println(strIn);
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File("e:/test/text2.txt")));
            bw.write(strIn);
            bw.flush();
            stdin.close();
            bw.close();
} catch(Exception e) ...{
           System.err.println(e.getMessage());
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.