String tokenizer和Scanner java

时间:2014-04-23 09:36:06

标签: java java.util.scanner stringtokenizer

我有一个大文本文件,我想用分隔符分隔成不同的字符串! - (每个字符串是多行)。

然后我要丢弃所有其他不包含的字符串:

===========  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.hasNextLine()){
            StringTokenizer st = new StringTokenizer(scan.nextLine(),"!-");
            if(st.equals("   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")) {
                System.out.print(st);
            }
        }
        scan.close();
    }
}

3 个答案:

答案 0 :(得分:0)

您应该考虑将java文档页面读到StringTokenizerhttp://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html

您的代码中存在两个不同的问题:

  1. 由于您所需的字符串不超过文件中的一行,因此您首先必须将它们添加到String中),然后通过StringTokenizer使用它再次分开。
  2. 您必须将StringTokenizer.nextToken()与支票String进行比较,而不是将整个StringTokenizer进行比较。 StringTokenizer.nextToken()然后会为您提供通过!-分隔的下一个字符串。
  3. 以下代码应该有效:

    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);
        //Scanning
        //first scan the whole file into a string (because a sting can have more than one line)
        String temp = "";
        while(scan.hasNextLine()){
            temp = scan.nextLine();
        }
        //now add the string to tokeinzer
        StringTokenizer st = new StringTokenizer(temp,"!-");
        //now give output
        while(st.hasMoreTokens()){
        String temp2 = st.nextToken();
            if(temp2.equals("   ===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")) {
                System.out.print(temp2);
            }
        }
        scan.close();
    }
    }
    }
    

答案 1 :(得分:0)

删除if条件并在条件

时添加以下内容
 while (st.hasMoreElements()) {
                        System.out.println(st.nextElement());
                    }

因为stringtokenizer基于令牌分割文本。所以你永远不会成真。

答案 2 :(得分:0)

试试这个...........

while(scan.hasNextLine()){
                StringTokenizer st = new StringTokenizer(scan.nextLine(),"!-");
                while(st.hasMoreTokens()){
                    String stt = st.nextElement().toString();
                    if(stt.equals("===========  ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")) {
                        System.out.print(stt);
                    }
                }
            }

你将字符串与stringtokenizer对象进行比较而不是值....