如何从Java中的文本文件中提取数据 [英] how to extract data from text file in Java

查看:126
本文介绍了如何从Java中的文本文件中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(myFile.hasNextLine()){



if(myFile.next()。equals() Oval)){
System.out.println(这是一个椭圆形);


$ b else if(myFile.next()。equals(Rectangle)){
System.out.println(this is a Rectangle );


$ / code $ / pre

文件包含以下
数据
椭圆形10 10 80 90红色

椭圆形20 20 50 60蓝色
矩形10 10 100 100绿色


我想提取数据并根据行开始处指定的类型将它们传递给特定的构造函数。

但是我越来越奇怪输出


这是线程main中的一个椭圆
异常java.util.NoSuchElementException
这是一个Rectangle
在java.util.Scanner.throwFor(Scanner.java:907)
这是一个Rectangle
在java.util.Scanner.next(Scanner.java:1416)
在TestMain.main(TestMain.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.ja va:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)


完成退出代码1的过程

解决方案

您需要将 next() hasNext()方法调用相匹配以匹配单个字符串令牌

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

if(token.equals(Oval)){
System.out.println(This is a Oval);
}
...
}


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

the file contains the following
Oval 10 10 80 90 Red
Oval 20 20 50 60 Blue
Rectangle 10 10 100 100 Green

I want to extract the data and pass them to a specific constructor according to the type indicated at the beginning of the line.

but I am getting this weird output

this is an Oval Exception in thread "main" java.util.NoSuchElementException this is an Rectangle at java.util.Scanner.throwFor(Scanner.java:907) this is an Rectangle at java.util.Scanner.next(Scanner.java:1416) at TestMain.main(TestMain.java:33) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Process finished with exit code 1

解决方案

You need to match your next() with a hasNext() method call to match an individual String token

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

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

这篇关于如何从Java中的文本文件中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆