我试图最终以 results.txt 减去任何匹配的项目,成功地将某些字符串输入与另一个.txt文件进行了比较。盯着这个代码太久了,我不知道为什么它不起作用。编码的新手,如果我可以朝正确的方向转向,那么会很感激!也许我需要一种不同的方法?对于您可能发出的任何喧闹声表示歉意。使用Java8。
//Sending a String[] into 'searchFile', contains around 8 small strings.
//Example of input: String[]{"name1","name2","name 3", "name 4.zip"}
^ This is my exclusions list.
public static void searchFile(String[] arr, String separator)
{
StringBuilder b = new StringBuilder();
for(int i = 0; i < arr.length; i++)
{
if(i != 0) b.append(separator);
b.append(arr[i]);
String findME = arr[i];
searchInfo(MyApp.getOptionsDir()+File.separator+"file-to-search.txt",findME);
}
}
^这很好。然后,我将结果发送到" SearchInfo",并尝试匹配和删除任何重复(完整而不是部分(字符串。这是我目前失败的地方。代码运行但不会产生我所需的输出。它通常会发现零件字符串而不是完整的字符串。我认为每次都会覆盖"结果"文件...但是我不确定tbh!
file-to-search.txt 包含:" name2"," name.zip"," name 3.zip"," name 4.zip"(文本文件只是一行(
public static String searchInfo(String fileName, String findME)
{
StringBuffer sb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while((line = br.readLine()) != null)
{
if(line.startsWith("""+findME+"""))
{
sb.append(line);
//tried various replace options with no joy
line = line.replaceFirst(findME+"?,", "");
//then goes off with results to create a txt file
FileHandling.createFile("results.txt",line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
我想最终要使用的是结果文件减去任何匹配的完整字符串(不是零件字符串(:
例如。 results.txt 最终以:" name.zip"," name 3.zip"
可以使用我拥有的信息。您可以做的是这个
List<String> result = new ArrayList<>();
String content = FileUtils.readFileToString(file, "UTF-8");
for (String s : content.split(", ")) {
if (!s.equals(findME)) { // assuming both have string quotes added already
result.add(s);
}
}
FileUtils.write(newFile, String.join(", ", result), "UTF-8");
使用Apache Commons File utils轻松。您可以根据需要在逗号后添加或删除空格。