我使用正則表達式解析文本文件以使用結果組一和二,如下所示:在另一個文件中寫入第二組使它的名字成為第一組不幸的是,沒有數據寫入文件!我沒有弄清楚問題出在哪里,這是我的代碼:package javaapplication5;import java.io.*;import java.util.regex.*; public class JavaApplication5 { public static void main(String[] args) { // TODO code application logic here try { FileInputStream fstream = new FileInputStream("C:/Users/Welcome/Desktop/End-End-Delay.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); File newFile1= new File("C:/Users/Welcome/Desktop/AUV1.txt"); FileOutputStream fos1= new FileOutputStream(newFile1); BufferedWriter bw1= new BufferedWriter(new OutputStreamWriter(fos1)); String strLine; while ((strLine = br.readLine()) != null) { Pattern p = Pattern.compile("sender\\sid:\\s(\\d+).*?End-End\\sDelay:(\\d+(?:\\.\\d+)?)"); Matcher m = p.matcher(strLine); while (m.find()) { String b = m.group(1); String c = m.group(2); int i = Integer.valueOf(b); if(i==0){ System.out.println(b); bw1.write(c); bw1.newLine(); } System.out.println(b); // System.out.println(c); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }}這里的任何人都可以幫助我解決這個問題并識別它嗎?
1 回答

慕仙森
TA貢獻1827條經驗 獲得超8個贊
您正在使用 BufferedWriter,并且永遠不會刷新(刷新寫入器將內容推送到磁盤上)您的寫入器,甚至在程序結束時關閉它。
因此,在您的內容從 BufferedWriter 寫入磁盤上的實際文件之前,程序會退出并且內容會丟失。
為避免這種情況,您可以在 bw1 中寫入內容后立即調用flush,
bw1.write(c);
bw1.newLine();
bw1.flush();
或者
在你的程序結束之前,你應該調用,
bw1.close(); // this ensures all content in buffered writer gets push to disk before jvm exists
不推薦每次寫入數據時調用flush,因為它違背了緩沖寫入的目的。
所以最好是關閉緩沖的 writer 對象。你可以通過兩種方式做到這一點
嘗試資源
最后手動關閉緩沖的 writer 對象,可能在 finally 塊中以確保它被調用。
除此之外,您還需要確保您的正則表達式與您的條件相匹配,
if(i==0){
被執行,否則在文件中寫入數據的代碼將不會被執行,當然在這種情況下,文件中不會發生寫入。
此外,強烈建議關閉您打開的任何資源,如文件資源、數據庫(連接、語句、結果集)資源等。
希望有幫助。
添加回答
舉報
0/150
提交
取消