基本文件读取到阵列存储

时间:2012-06-24 21:16:39

标签: java arrays file-io collections methods

我有一个简单的Java问题,如果可能的话我需要一个简单的答案。我需要从文件中输入数据并将数据存储到数组中。为此,我必须让程序打开数据文件,计算文件中的元素数量,关闭文件,初始化数组,重新打开文件并将数据加载到数组中。我主要是在将文件数据存储为数组时遇到问题。这就是我所拥有的:

要阅读的文件位于:https://www.dropbox.com/s/0ylb3iloj9af7qz/scores.txt

import java.io.*;
import java.util.*;
import javax.swing.*;
import java.text.*;


public class StandardizedScore8
{



//Accounting for a potential exception and exception subclasses
public static void main(String[] args) throws IOException
{
    // TODO a LOT
    String filename;
    int i=0;


    Scanner scan = new Scanner(System.in);
    System.out.println("\nEnter the file name:");
    filename=scan.nextLine();



    File file = new File(filename);


    //File file = new File ("scores.txt");
    Scanner inputFile = new Scanner (file);

    String [] fileArray = new String [filename];
    //Scanner inFile = new Scanner (new File ("scores.txt"));

    //User-input
//  System.out.println("Reading from 'scores.txt'");
//  System.out.println("\nEnter the file name:");
//  filename=scan.nextLine();

    //File-naming/retrieving
//  File file = new File(filename);
//  Scanner inputFile = new Scanner(file);

4 个答案:

答案 0 :(得分:2)

我建议你使用Collection。这样,您不必事先知道文件的大小,只读一次,而不是两次。该系列将管理自己的尺寸。

答案 1 :(得分:1)

是的,如果你不关心两次做事的麻烦,你可以。使用while(inputFile.hasNext()) i++;

计算元素数量并创建数组:

String[] scores = new String[i];

如果你关心,请使用列表而不是数组:

List<String> list = new ArrayList<String>();
while(inputFile.hasNext()) list.add(inputFile.next());

您可以获取list.get(i)等列表元素,设置列表元素list.set(i,"string"),并获取列表list.size()的长度。

顺便说一句,您的String [] fileArray = new String [filename];行不正确。您需要使用int来创建数组而不是String。

答案 2 :(得分:1)

/*
 * Do it the easy way using a List
 *
 */

public static void main(String[] args) throws IOException
{
    Scanner scan = new Scanner(System.in);
    System.out.println("\nEnter the file name:");
    String filename = scan.nextLine();

    FileReader fileReader = new FileReader(filename);
    BufferedReader reader = new BufferedReader(fileReader);

    List<String> lineList = new ArrayList<String>();
    String thisLine = reader.readLine();

    while (thisLine != null) {
        lineList.add(thisLine);
        thisLine = reader.readLine();
    }

    // test it

    int i = 0;
    for (String testLine : lineList) {
        System.out.println("Line " + i + ": " + testLine);
        i++;
    }
}

答案 3 :(得分:1)

我们可以使用ArrayList集合将文件中的值存储到数组中,而无需事先知道数组的大小。 您可以从以下网址获取有关ArrayList集合的更多信息。

http://docs.oracle.com/javase/tutorial/collections/implementations/index.html

http://www.java-samples.com/showtutorial.php?tutorialid=234