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

♀尐吖头ヾ 提交于 2019-12-11 19:47:36

问题


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

回答1:


use below code, scanner next gives just a word use nextLine instead to read whole line..

Scanner scan = new Scanner(file);
            String str1 = scan.nextLine();

                if(str1.equals("!-   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ==========="))
                    System.out.println(str1);
                scan.close();



回答2:


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


来源:https://stackoverflow.com/questions/23220224/using-scanner-to-read-string-from-text-file-and-then-print-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!