检查将要写入文本文件的字符串/行是否已存在于文本文件中
我正在分析Web访问日志并尝试找出所有唯一对象(任何文件或任何路径)在访问日志中只请求一次。每次节目写入到文本文件,文本文件的内容是这样的:检查将要写入文本文件的字符串/行是否已存在于文本文件中
/~scottp/publish.html
/~ladd/ostriches.html
/~scottp/publish.html
/~lowey/
/~lowey/kevin.gif
/~friesend/tolkien/rootpage.html
/~scottp/free.html
/~friesend/tolkien/rootpage.html
.
.
.
我要检查,如果这是要写入文本文件中的行已经在文本文件中存在。换句话说,如果它在文本文件中确实存在,则什么也不做,并跳过它并分析下一行。如果不是,则将其写入文本文件。
我试图用equals
或contains
但它并不似乎是工作,这里是我的代码有点件:
// Find Unique Object that were requested only once
if (matcher3.find()) {
if(!requestFileName.equals(bw.equals(requestFileName))) {
bw.write(requestFileName);
bw.newLine();
}
}
我应该怎么做,以实际执行的检查?
由于@JB Nizet评论你应该设置的使用
Set<String> set = new HashSet<String>();
BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/yourFile.txt")));
String line;
while((line = reader.readLine()) != null) {
// duplicate
if(set.contains(line))
continue;
set.add(line);
// do your work here
}
为什么设置
不保留jvm堆中的所有字符串 – guleryuz
然后你将有一个程序消耗更少的内存,但是不正确。先尝试正确。优化之后,并且只在需要时,并且不会影响正确性。 –
也许简单的东西是这样的:
try (BufferedReader br = new BufferedReader(new FileReader(yourFilePath))) {
boolean lineExists = false;
String currentLine;
while ((currentLine = br.readLine()) != null) {
if (currentLine.trim().equalsIgnoreCase(requestFileName.trim())) {
lineExists = true;
break;
}
}
br.close();
if (!lineExists) {
bw.write(requestFileName);
bw.newLine();
}
}
catch (IOException e) {
// Do what you want with Exception...
}
这是很难以帮助这个微小的,断章取义的代码片断。但是可以肯定的是,'requestFileName'很可能是一个String,它永远不会等于'bw.equals(requestFileName)'返回的布尔值。 'bw',可能是一个BufferedWriter,永远不会等于'requestFileName',它是一个String。您需要将行存储在Set中,并在将其写入文件之前检查Set中是否包含下一行。 –