解析文本文件转换成字符串(JAVA) [英] Parsing a text file into strings (JAVA)

查看:198
本文介绍了解析文本文件转换成字符串(JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个codeD读取文本文件到一个数组列表。不过,我不能确定如何解析我的文本文件转换成字符串正确地被放入一个数组列表。这里是我需要使用一个示例文本文件。

这应该是样品的问题。

  2




0
4
6

我的Java code以下:

 包javaapplication8;进口的java.util。*;
进口java.io. *;
公共类JavaApplication8 {
公共静态无效的主要(字串[] args)抛出IOException    扫描仪inScan =新的扫描仪(System.in);    串FILE_NAME;
    System.out.print(什么是完整的文件路径名\\ n>>);
    FILE_NAME = inScan.next();    扫描仪FSCAN =新的扫描仪(新文件(FILE_NAME));
    INT numItems的=的Integer.parseInt(fScan.nextLine());
    ArrayList的<串GT;问题=新的ArrayList<串GT;();    的for(int i = 0; I< numItems的;我++)
    {
        Questions.add(fScan.nextLine());
    }    System.out.print(数组是:+问题);}


解决方案

从你对变量 numLines 下面的评论,你并不需要从内容解析整数这样你就可以删除行:

  INT numItems的=的Integer.parseInt(fScan.nextLine());

然后输出每行的数组,可以使用 Scanner.hasNextLine()

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

I am trying to write a coded that reads in a text file into an array list. However, I am unsure how to parse my text file into strings to correctly be put into an array list. Here is a sample text file that I need to use.

This should be the sample question.

2
one
two
three
four
0
4
6

My Java code below:

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



}

解决方案

From your comment about the variable numLines below, you don't need to parse integers from the content so you can remove the line:

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

Then to output every line to the array, you can use Scanner.hasNextLine():

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

这篇关于解析文本文件转换成字符串(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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