简体   繁体   English

使用扫描仪从文本文件中读取字符串,然后打印出

[英]Using scanner to read string from text file and then print out

I have a text file which has the string, - "!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========" in it as you can see in the code below. 我有一个文本文件,其中包含字符串- "!- =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="请参见下面的代码。 IF the text file contains this string I need to read it from the text file and then print it out again. 如果文本文件包含此字符串,则需要从文本文件中读取它,然后再次打印出来。 The problem is I cant work out why my code is not printing it. 问题是我无法弄清楚为什么我的代码没有打印出来。

Any help would be appreciated thanks! 任何帮助,将不胜感激,谢谢!

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();
        }   
}

use below code, scanner next gives just a word use nextLine instead to read whole line.. 使用以下代码,扫描仪接下来仅给出一个单词,使用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();

use this 用这个

if(str.equals("!-   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")){
            System.out.print(str);
        }

instead of 代替

if(str == "!-   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="){
            System.out.print(str);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM