Java IO讀檔案和寫檔案

來源:互聯網
上載者:User

寫檔案Java代碼:

package hand.wang.test;</p><p>import java.io.*;</p><p>public class write {<br /> public static void main(String[] args) {<br /> write("E://123.txt", "hello");<br /> }</p><p> public static void write(String path, String content) {<br /> String s = new String();<br /> String s1 = new String();</p><p> try {<br /> File f = new File(path);</p><p> if (f.exists()) {<br /> System.out.println("檔案存在");<br /> } else {<br /> System.out.println("檔案不存在,正在建立...");<br /> if (f.createNewFile()) {<br /> System.out.println("檔案建立成功!");<br /> } else {<br /> System.out.println("檔案建立失敗!");<br /> }<br /> }</p><p> BufferedReader input = new BufferedReader(new FileReader(f));</p><p> while ((s = input.readLine()) != null) {<br /> s1 += s + "/n";<br /> }</p><p> System.out.println("檔案內容:" + s1);<br /> input.close();<br /> s1 += content;<br /> BufferedWriter output = new BufferedWriter(new FileWriter(f));<br /> output.write(s1);<br /> output.close();<br /> } catch (Exception e) {<br /> e.printStackTrace();<br /> }<br /> }<br />}

 

讀檔案Java代碼:

package hand.wang.test;</p><p>import java.io.BufferedReader;<br />import java.io.File;<br />import java.io.FileInputStream;<br />import java.io.FileNotFoundException;<br />import java.io.InputStreamReader;</p><p>public class Read {<br /> public static void main(String[] args) {<br /> read("E://123.txt");<br /> }</p><p> public static void read(String file) {<br /> String s = null;<br /> StringBuffer sb = new StringBuffer();<br /> File f = new File(file);<br /> if (f.exists()) {<br /> try {<br /> BufferedReader br =<br /> new BufferedReader(new InputStreamReader(new FileInputStream(f)));<br /> while ((s = br.readLine()) != null) {<br /> sb.append(s);<br /> }<br /> System.out.println(sb);<br /> } catch (Exception e) {<br /> e.printStackTrace();<br /> }<br /> } else {<br /> System.out.println("檔案不存在!");<br /> }<br /> }<br />}

 

相關文章

聯繫我們

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