我使用正则表达式解析文本文件,以使用结果组一和组二,如下所示:
不幸的是,文件中没有写入任何数据!我不知道问题出在哪里,下面是我的代码:
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());
}
}
}
在座的任何人能帮我解决这个问题并识别它吗?
发布于 2018-10-28 04:19:54
您正在使用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,因为它违背了缓冲写入的目的。
所以最好的方法是关闭缓冲的写入器对象。你可以通过两种方式来实现,
除此之外,您还需要确保您的正则表达式与您的条件匹配,
if(i==0){
否则,在文件中写入数据的代码将不会被执行,当然,在这种情况下,在文件中也不会发生写入。
此外,强烈建议关闭您打开的任何资源,如文件资源、数据库(连接、语句、ResultSets)资源等。
希望这能有所帮助。
https://stackoverflow.com/questions/53025620
复制相似问题