我有一个文本文件,其中包含字符串 - "!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="
,如下面的代码所示。如果文本文件包含此字符串,我需要从文本文件中读取它,然后再次打印出来。问题是我无法弄清楚为什么我的代码不打印它。
任何帮助将不胜感激!
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:/Users/Anton/Pictures/1 x geotransform0.5m shading.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext()){
String str = scan.next();
if(str == "!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="){
System.out.print(str);
}
}
scan.close();
}
}
答案 0 :(得分:1)
使用下面的代码,扫描仪接下来只给出一个单词使用nextLine而不是读取整行...
Scanner scan = new Scanner(file);
String str1 = scan.nextLine();
if(str1.equals("!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="))
System.out.println(str1);
scan.close();
答案 1 :(得分:0)
使用此
if(str.equals("!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")){
System.out.print(str);
}
而不是
if(str == "!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="){
System.out.print(str);
}