我已经通过使用这里的方法实现了从外部文本文件返回文本
FileReader reader = new FileReader("C:\\Users\\boung\\Desktop\\usernames.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
此方法打印
username1
但现在我想做的是,我想获取从文本文件返回的文本,并将其与程序中已设置的字符串进行比较。像这样:
String S = "username1";
FileReader reader = new FileReader("C:\\Users\\boung\\Desktop\\usernames.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
if (character.contains(S)) {
System.out.println("username1 found");
}
但我无法比较character
和S
。
我需要能够将从 .txt 文件返回的所有文本进行字符串化,并检查该文件是否包含我正在查找的某个字符串。有人可以帮忙吗?
最佳答案
您需要读取文件,而不是逐个字符,而是整个字符串 您可以使用下一个代码
String S = "username1";
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines( Paths.get("C:\\Users\\boung\\Desktop\\usernames.txt"), StandardCharsets.UTF_8))
{
stream.forEach(s -> contentBuilder.append(s).append("\n"));
}
catch (IOException e)
{
e.printStackTrace();
}
if (contentBuilder.toString().contains(S)) {
System.out.println("username1 found");
}
```
关于java - 如何将外部 .txt 文件中的文本与字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150517/