繁体   English   中英

如何从Java中的文本文件中提取数据

[英]how to extract data from text file in Java

while (myFile.hasNextLine()) {

if(myFile.next().equals("Oval")) { System.out.println("this is an Oval"); } else if(myFile.next().equals("Rectangle")) { System.out.println("this is an Rectangle"); }

该文件包含以下内容
椭圆10 10 80 90红色
椭圆20 20 50 60蓝色
矩形10 10100100绿色

我想提取数据并将其根据行开头指示的类型传递给特定的构造函数。

但我得到这个奇怪的输出

这是线程“ main”中的卵形异常java.util.NoSuchElementException这是java.util.Scanner.throwFor(Scanner.java:907)处的矩形。这是java.util.Scanner.next(Scanner.java)中的矩形。 :1416)位于sun.reflect.NativeMethodAccessorImpl.invoke的TestMain.main(TestMain.java:33)invoke0(位于sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethod)的本地方法)(NativeMethodAccessorImpl.java:57)位于sun.reflect.DelegatingMethodAccessorImpl.invoke(在com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)处java.lang.reflect.Method.invoke(Method.java:601)处的DelegatingMethodAccessorImpl.java:43)

流程以退出代码1完成

请理解,当您在Scanner对象上调用next()时,它将吞噬下一个令牌,然后将其返回给您。 如果不将返回的String分配给变量,它将永远丢失,并且下次调用next()您将获得一个新令牌。 获得令牌更好,将其分配给String变量,然后进行if测试。 不要在if布尔测试块中调用next()

即,类似:

while (myFile.hasNextLine()) {

    // get the token **once** and assign it to a local variable
    String text = myFile.nextLine();

    // now use the local variable to your heart's content    
    if(text.equals("Oval")) {
        System.out.println("this is an Oval");

    }

    else if(text.equals("Rectangle")) {
        System.out.println("this is an Rectangle");

    } 

另外,如果您测试hasNextLine() ,则应调用nextLine() ,而不要调用next() ,并且对于每个hasNextLine只能调用一次


从文本文件提取数据行时,有时会使用多个Scanner。 例如:

Scanner fileScanner = new Scanner(myFile);
while (fileScanner.hasNextLine()) {
  Scanner lineScanner = new Scanner(fileScanner.nextLine());

  // use the lineScanner to extract tokens from the line

  lineScanner.close();
}
fileScanner.close(); // likely done in a finally block after null check

您需要将next()hasNext()方法调用进行匹配,以匹配单个String令牌

while (myFile.hasNext()) {
   String token = myFile.next();

    if (token.equals("Oval")) {
       System.out.println("this is an Oval");
    }
    ...
}

暂无
暂无

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

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