java Java如何将文本文件中的数据读入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16086935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:51:51  来源:igfitidea点击:

How to read data from a text file into arrays in Java

javaarraysfile

提问by Java Coder

I am having trouble with a programming assignment. I need to read data from a txt file and store it in parallel arrays. The txt file contents are formatted like this:

我在编程作业时遇到问题。我需要从 txt 文件中读取数据并将其存储在并行数组中。txt 文件内容的格式如下:

Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9

Note: The "Line1: ", "Line2: ", etc is just for display purposes and isn't actually in the txt file.

注意:“Line1:”、“Line2:”等仅用于显示目的,实际上并不在 txt 文件中。

As you can see it goes in a pattern of threes. Each entry to the txt file is three lines, two strings and one int.

正如你所看到的,它是一个三分的模式。txt 文件的每个条目都是三行,两个字符串和一个 int。

I would like to read the first line into an array, the second into another, and the third into an int array. Then the fourth line would be added to the first array, the 5th line to the second array and the 6th line into the third array.

我想将第一行读入一个数组,第二行读入另一个,第三行读入一个 int 数组。然后将第四行添加到第一个数组中,将第 5 行添加到第二个数组中,将第 6 行添加到第三个数组中。

I have tried to write the code for this but can't get it working:

我试图为此编写代码,但无法使其正常工作:

//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];

String fileName = "myfile.txt";


readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);

private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {

        // Create File Object 
        File file = new File(fileName);

        if (file.exists())
        {

            Scanner scan = new Scanner(file);
            int counter = 0;

            while(scan.hasNext())
            {


                String code = scan.next();
                String moduleName = scan.next();
                int totalPurchase = scan.nextInt();

                moduleCodes[counter] = code;
                moduleNames[counter] = moduleName;
                numberOfStudents[counter] = totalPurchase;

                counter++; 


            }

        }

    }

The above code doesn't work properly. When I try to print out an element of the array. it returns null for the string arrays and 0 for the int arrays suggesting that the code to read the data in isn't working.

上面的代码不能正常工作。当我尝试打印出数组的一个元素时。它为字符串数组返回 null,为 int 数组返回 0,这表明读取数据的代码不起作用。

Any suggestions or guidance much appreciated as it's getting frustrating at this point.

任何建议或指导都非常感谢,因为此时它变得令人沮丧。

回答by Bernhard Barker

The fact that only null's get printed suggests that the file doesn't exist or is empty (if you print it correctly).

only null's get print的事实表明该文件不存在或为空(如果您正确打印)。

It's a good idea to put in some checking to make sure everything is fine:

进行一些检查以确保一切正常是个好主意:

if (!file.exists())
  System.out.println("The file " + fileName + " doesn't exist!");

Or you can actually just skip the above and also take out the if (file.exists())line in your code and let the FileNotFoundExceptionget thrown.

或者您实际上可以跳过上面的内容,并if (file.exists())在您的代码中取出该行并让其FileNotFoundException抛出。

Another problem is that nextsplits things by white-space (by default), the problem is that there is white-space on that second line.

另一个问题是next按空白(默认情况下)分割事物,问题是第二行有空白。

nextLineshould work:

nextLine应该管用:

String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.parseInt(scan.nextLine());

Or, changing the delimiter should also work: (with your code as is)

或者,更改分隔符也应该有效:(按原样使用您的代码)

scan.useDelimiter("\r?\n");

回答by Mohammad Adil

  String code = scan.nextLine();
  String moduleName = scan.nextLine();
  int totalPurchase = scan.nextInt();
  scan.nextLine()

This will move scanner to proper position after reading int.

这将在阅读后将扫描仪移动到适当的位置int

回答by Achintya Jha

You are reading line so try this:

你正在阅读线所以试试这个:

while(scan.hasNextLine()){
    String code = scan.nextLine();
    String moduleName = scan.nextLine();
    int totalPurchase = Integer.pasreInt(scan.nextLine().trim());

    moduleCodes[counter] = code;
    moduleNames[counter] = moduleName;
    numberOfStudents[counter] = totalPurchase;
    counter++; 
}