在文件中查找包含文本的行。

huangapple go评论139阅读模式
英文:

Find line with text in a file

问题

我想要在 options.bldata 中查找是否有写入 firstLaunch=,为此我编写了以下代码:

File file = new File("options.bldata");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if (line.equals("firstLaunch=")) {
        System.out.println("123");
    }
}

当它找到一行包含 firstLaunch= 的内容时,它应该打印出 123。但是我不知道为什么即使 firstLaunch= 存在于文件中,它也没有打印出 123。

英文:

I wanted to find out in options.bldata if firstLaunch= was written, for this I wrote the following code:

File file = new File("options.bldata");
	Scanner scanner = new Scanner(file);
	while (scanner.hasNextLine()) {
		
		String line = scanner.nextLine();
		if (line == "firstLaunch=") {
			
			System.out.println("123");
			
		}
		
	}

when it finds a line with firstLaunch= it should print 123, but I don't know why it doesn't print 123 even if firstLaunch= is in the file.

答案1

得分: 2

Operator == 检查两个对象是否指向同一内存位置,而 .equals() 方法评估对象中的值进行比较。

while (scanner.hasNextLine()) { 
    String line = scanner.nextLine();
    if (line.equals("firstLaunch=")) {   
        System.out.println("123");   
    }   
}

这里有一篇文章提供更多信息

英文:

Operator == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.

while (scanner.hasNextLine()) { 
        String line = scanner.nextLine();
        if (line.equals("firstLaunch=")) {   
            System.out.println("123");   
        }   
    }

Here is an article for more information

答案2

得分: 1

代码中有两个错误之处。

  1. 永远不要使用双等号来比较字符串。你需要使用字符串的 equals() 函数来进行比较。
  2. 你想要测试的是字符串 firstLaunch= 是否在这一行中,而不是你的行是否等于 firstLaunch=。为此,你可以使用 line.contains("firstLaunch=")
英文:

There is two wrong thing in the code.

  1. Never use double equals to compare strings. You need to use the equals() function from string to do so
  2. you want to test if the string firstLaunch= is in the line, not that your line is equals to firstLaunch=. For this, you can use line.contains("firstLaunch=")

答案3

得分: 1

你应该使用 equals() 来比较字符串。或者在你的情况下,使用 contains(),因为该行可能还有其他内容,不仅仅是你想要查找的部分。

英文:

You should use equals() to compare strings. Or in your case, contains() because the line might have other stuff, not just what you want to find

huangapple
  • 本文由 发表于 2020年8月23日 04:30:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63540824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定