我有一个日志包。我想过滤 log.e,并将其保存到另一个文件。但是我发现 BufferedWriter 达不到预期的效果。比如下面的日志文件中的两行不能存储另一个文件。
E/Vold ( 96): Sleep 2s to make sure that coldboot() events are handled
E/WindowManager( 244): setEventDispatching false
附上代码:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSpider {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\log.txt"));
String line = "";
try {
while((line = bufferedReader.readLine())!=null)
{
Parseelog(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line)
{
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\logspider2.txt"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Pattern pattern = Pattern.compile("[\\w[.-]]+\\@[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
while(matcher.find())
{
String string = new String(matcher.group());
string += "\n";
System.out.println(string); //here can print the search results
try {
bufferedWriter.write(string, 0, string.length());
bufferedWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}