這篇文章主要介紹Java如何按行讀取文件以及按行寫入文件,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
首先是按行讀取字符串
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class TxtChange { public static void main(String[] args){ File file=new File("E:\\oldData.txt"); BufferedReader reader=null; String temp=null; int line=1; try{ reader=new BufferedReader(new FileReader(file)); while((temp=reader.readLine())!=null){ // System.out.println("第"+line+"行:"+temp); String string=AnalyzeStr.getAnalyze().getNewString(temp);//調(diào)用分割方法 System.out.println(string); AnalyzeStr.getAnalyze().saveRecordInFile(string);//調(diào)用按行存儲字符串 line++; } } catch(Exception e){ e.printStackTrace(); } finally{ if(reader!=null){ try{ reader.close(); } catch(Exception e){ e.printStackTrace(); } } } } }
按照空格分割字符串并重新組合成新的字符串
空是”\s”,是轉義字符,需要使用”\s”,“+”代表一個或者多個空格
public String getNewString(String fileName){ String str1=""; String str2=""; String str3=""; String []arrayStr=fileName.split("\\s+"); str1="\n\t\t"+arrayStr[0]; str2="\t"+arrayStr[1]; str3="\t"+arrayStr[2]; return str1+str2+str3; }
然后按行保存字符串方法,path是保存的路徑,例如“D://test.txt”
//追加記錄 public void saveRecordInFile(String str) { File record = new File(path);//記錄結果文件 try { if (!record.exists()) { File dir = new File(record.getParent()); dir.mkdirs(); record.createNewFile(); } FileWriter writer = null; try { // 打開一個寫文件器,構造函數(shù)中的第二個參數(shù)true表示以追加形式寫文件 writer = new FileWriter(record, true); writer.write(str); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { System.out.println("記錄保存失敗"); } }
以上是“Java如何按行讀取文件以及按行寫入文件”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
文章標題:Java如何按行讀取文件以及按行寫入文件-創(chuàng)新互聯(lián)
URL標題:http://vcdvsql.cn/article32/pghpc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供ChatGPT、網(wǎng)站制作、網(wǎng)站設計、企業(yè)建站、虛擬主機、關鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容