【问题标题】:Parsing a text file into strings (JAVA)将文本文件解析为字符串 (JAVA)
【发布时间】:2012-10-22 15:12:51
【问题描述】:

我正在尝试编写一个将文本文件读入数组列表的编码。但是,我不确定如何将我的文本文件解析为字符串以正确放入数组列表中。这是我需要使用的示例文本文件。

这应该是示例问题。

2
one
two
three
four
0
4
6

我的 Java 代码如下:

package javaapplication8;

import java.util.*;
import java.io.*;
public class JavaApplication8 {


public static void main(String[] args) throws IOException{

    Scanner inScan = new Scanner(System.in);

    String file_name;
    System.out.print("What is the full file path name?\n>>");
    file_name = inScan.next();

    Scanner fScan = new Scanner(new File(file_name));
    int numItems = Integer.parseInt(fScan.nextLine());
    ArrayList<String> Questions = new ArrayList<String>();

    for(int i=0; i < numItems; i++)
    {
        Questions.add(fScan.nextLine());
    }

    System.out.print("The array is: " + Questions);



}

【问题讨论】:

  • 文件中每个值之间是否包含空格??

标签: java arrays file list text


【解决方案1】:

根据您对下面变量 numLines 的评论,您无需从内容中解析整数,因此可以删除该行:

int numItems = Integer.parseInt(fScan.nextLine());

然后要将每一行输出到数组中,可以使用Scanner.hasNextLine()

while (fScan.hasNextLine()) {
   questions.add(fScan.nextLine());
}

【讨论】:

  • numItems的意义是什么?为什么不进行开放式阅读?您的预期输出是什么?
  • 我不知道为什么我没有得到相同的输出。我的输出是一个错误代码:线程“主”java.lang.NumberFormatException 中的异常:对于输入字符串:java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 的 java.lang 中的“这应该是问题”。 Integer.parseInt(Integer.java:492) 在 java.lang.Integer.parseInt(Integer.java:527) 在 javaapplication8.JavaApplication8.main(JavaApplication8.java:23) Java 结果:1
  • 我不知道为什么,但我的代码只是给了我想要的输出。非常感谢
  • Integer.parseInt(...) 期望Strings,格式为ints,否则抛出NumberFormatException
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2012-11-08
  • 1970-01-01
相关资源
最近更新 更多