我正在寻找一种方法来比较字符串(在本例中是文本文件中的一行)与数组中的每个元素,并查看是否存在匹配。在高级概述中,我有一个字符串数组(大约100个元素),其中包含所有字符串,这些字符串都包含在需要删除的文件中。所以我正在将一个文件读入StringBuffer并写入每一行,除了跳过与数组中的元素匹配的所有行。这就是我到目前为止所做的:
//Main Class calling the method
public class TestApp {
public static void main(String[] args) {
CompareAndDelete.RemoveDuplicateLines("C:/somelocation", 2Darray);
}
}
public class CompareAndDelete {
static string Line_of_Text;
static StringBuffer localBuff = new StringBuffer();
static FileReader Buffer;
static BufferedReader User_File;
public static void RemoveDuplicateLines(String local, String[][] duplicates) throws IOException
{
//Converting 2D array to one-dimensional array
final String[] finalDups = new String[duplicates.length];
for(int i = 0; i < duplicates.length; i++)
{
finalDups[i] = duplicates[i][0]+" "+duplicates[i][1];
}
int count = 0;
User_File = new BufferedReader(Buffer);
Set<String> Values = new HashSet<String>(Arrays.asList(finalDups));
while((Line_of_Text = User_File.readLine()) != null){
if(!(Values.contains(Line_of_Text))){
localBuff.append(Line_of_Text+"\n");
}else{
count++;
}
}
System.out.println(count);
//Printing StringBuffer to file
BufferedWriter testOutFile = new BufferedWriter(new FileWriter("C:/test.txt"));
testOutFile.write(localBuff.toString());
testOutFile.flush();
testOutFile.close();
}
所以我不确定IF的声明,我知道它不能正常工作,它目前只删除新StringBuffer中的前几个元素,因为这些行碰巧是朝向文件的末尾,它确实不要重新检查每一行与每个元素的匹配。我知道必须有更好的方法来做到这一点......提前感谢任何帮助/建议。
**更新:使用上面的代码,它现在在此行上抛出以下错误:
while((Line_of_Text = User_File.readLine()) != null){
错误:
Exception in thread "main" java.io.IOException: Stream closed
at sun.nio.cs.StreamDecoder.ensureOpen(StreamDecoder.java:51)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:204)
at java.io.InputStreamReader.read(InputStreamReader.java:188)
at java.io.BufferedReader.fill(BufferedReader.java:147)
at java.io.BufferedReader.readLine(BufferedReader.java:310)
at java.io.BufferedReader.readLine(BufferedReader.java:373)
at compare.CompareAndDelete.RemoveDuplicateLines(CompareAndDelete.java:48)
at mainPackage.TestApp.main(TestApp.java:326)
答案 0 :(得分:0)
通过将String
数组成员添加到Set
,然后检查是否设置contains()
当前行,可以非常有效地完成此操作。例如:
Set<String> ignoredStrings = new HashSet<String>(Arrays.asList(arr));
String line;
while ((line = file.readLine()) != null) {
if (!ignoredStrings.contains(line)) {
buffer.append(line);
buffer.append("\n");
}
}
答案 1 :(得分:0)
这是一种方法:
public boolean isStringInArray(String str, String[] strarr){
for(String s: strarr){
if(str.equals(s)) return true;
}
return false
}
isStringInArray("Hello", new String[]{"Hello", "World"}); // True
isStringInArray("Hello", new String[]{"hello", "World"}); // False