一些 java檔案的操作樣本

來源:互聯網
上載者:User

java追加內容到檔案末尾

/**<br /> * 追加檔案:使用FileWriter<br /> *<br /> * @param fileName<br /> * @param content<br /> */<br /> public static void method2(String fileName, String content) {<br /> try {<br /> // 開啟一個寫檔案器,建構函式中的第二個參數true表示以追加形式寫檔案<br /> FileWriter writer = new FileWriter(fileName, true);<br /> writer.write(content);<br /> writer.close();<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }  

 

1.按行讀

try {<br /> String line;<br /> int i=0,count=0;<br /> File file=new File("infname");<br /> FileReader fr=new FileReader(file);//建立FileReader對象,並執行個體化為fr<br /> BufferedReader br=new BufferedReader(fr);//建立BufferedReader對象,並執行個體化為br<br /> br.mark((int)file.length()+1);<br /> while(br.readLine()!=null)count++;//擷取行數(沒有直接擷取行數的方法)<br /> String []lines=new String[count];<br /> br.reset();//重設檔案寫位置為開始<br /> line=(String)br.readLine();//讀取一行<br /> while(line!=null){<br /> lines[i++]=line;<br /> line=(String)br.readLine();<br /> }<br /> br.close();//關閉BufferedReader對象<br /> fr.close();//關閉檔案<br /> return lines;<br /> } catch (FileNotFoundException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> return null;<br /> } catch (IOException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> return null;<br /> } 

 

按行寫

try{<br /> FileWriter fw = new FileWriter("outfname.txt");<br /> PrintWriter fout = new PrintWriter(fw);<br /> fout.print("a");//不帶換行<br /> fout.print("b");<br /> fout.println("c");//帶換行<br /> fout.close();//這兩個一定要,不然你會發現檔案空的<br /> fw.close();<br />} catch (IOException e) {<br /> e.printStackTrace();<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.