Java 创建一个构造函数来读取一个txt文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20365379/
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-08-13 01:24:26  来源:igfitidea点击:

Creating a constructor to read a txt file

javaarraystextconstructor

提问by user2985542

I am creating a program that will produces the statistics of a baseball team

我正在创建一个程序来生成棒球队的统计数据

i am trying to create a constructor to read the file into the teamName instance variable and the battingAverages array.

我正在尝试创建一个构造函数来将文件读入 teamName 实例变量和 battingAverages 数组。

the txt file contains the one word name of the team followed by 20 batting averages.

txt 文件包含球队的一个单词名称,后跟 20 个击球平均值。

"Tars 0.592 0.427 0.194 0.445 0.127 0.483 0.352 0.190 0.335 0.207 0.116 0.387 0.243 0.225 0.401 0.382 0.556 0.319 0.475 0.279 "

"焦油 0.592 0.427 0.194 0.445 0.127 0.483 0.352 0.190 0.335 0.207 0.116 0.387 0.243 0.225 0.401 .0.40595 0.401 .0.3595

I am struggling to find how to go about this and get it started?

我正在努力寻找如何解决这个问题并开始使用它?

采纳答案by McProgramming

I ran this and this might be close to what you want. Instead of making a confusing constructor, make a private method that the constructor will call to read in the file into the array.

我跑了这个,这可能接近你想要的。不要创建一个令人困惑的构造函数,而是创建一个私有方法,构造函数将调用该方法将文件读入数组。

 import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;



public class Baseball {

    private File textFile;
    private Scanner input;
    private String teamName;

    //this will only work if you know there will be 20 entries everytime
    //otherwise I recommend loading the data into an ArrayList
    private double []battingAvgs = new double[20];

    public Baseball(String file){
        textFile = new File(file);
        readInFile(textFile);

    }

    //private method that reads in the file into an array 
    private void readInFile(File textFile){
        try {
            input = new Scanner(textFile);

            //read first string into variable teamName
            teamName = input.next();

            int i=0;
            //iterate through rest of file adding it to an ArrayList
            while(input.hasNext()){
                battingAvgs[i] = input.nextDouble();
                i++;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    //print out array
    public void printArray(){
        for(Double a: battingAvgs){
            System.out.println(a);
        }
    }

}

回答by Vineet Kosaraju

Well, if these are all on one line in a specific file then what you could do is construct a bufferedreader to read the first line of your file, split the line based on spaces, and then parse the teamName and batting averages out.

好吧,如果这些都在特定文件的一行上,那么您可以做的是构建一个缓冲读取器来读取文件的第一行,根据空格拆分该行,然后解析 teamName 并计算出击球平均值。

BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
String[] line = br.readLine().split(" ");
br.close();
teamName = line[0];
battingAverages = new int[20];
for(int i = 0; i < 20; i++)
    battingAverages[i] = Integer.parseInt(line[i+1]);

These might throw IOExceptions, which you will need to catch. I think Java 7 has a method to automatically handle these kinds of errors (not sure about this), but as I am new to Java 7's added functionality, I would just manually check for those exceptions.

这些可能会抛出 IOExceptions,您需要捕获它们。我认为 Java 7 有一种方法可以自动处理这些类型的错误(对此不确定),但由于我是 Java 7 新增功能的新手,我只会手动检查这些异常。

回答by Matthew S.

You need to use the BufferedReader, FileInputStream, and InputStreamReader. Your file.txt should have the batting averages on every line, as shown below.

您需要使用的BufferedReaderFileInputStreamInputStreamReader。您的 file.txt 应该在每一行都有击球率平均值,如下所示。

0.592
0.427
0.194

Here is an example of a class that when created, it will read a text file line by line and add each line to the array list:

这是一个类的示例,该类在创建时将逐行读取文本文件并将每一行添加到数组列表中:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;

public class Class {
    ArrayList<Double> averages;

    public Class() {
        averages = new ArrayList<Double>();
        try {
            FileInputStream in = new FileInputStream("inputFile.txt"); //your file path/name
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            while((strLine = br.readLine())!= null) averages.add(Double.parseDouble(strLine));

        }catch(Exception e){
            System.out.println(e);
        }

     }
}

Hope this helps

希望这可以帮助

回答by user3062600

Try using the Scannerclass.

尝试使用Scanner类。

File file=new File("TestFile.txt"); //Create a new file
Scanner scan=new Scanner(file);//Create a Scanner object (Throws FileNotFoundException)
if(scan.hasNext())  //Check to make sure that there is actually something in the file.
{
    String line=scan.nextLine();    //Read the line of data
    String[] array=line.split(" "); //Split line into the different parts
    teamName=array[0];  //The team name is located in the first index of the array
    battingAverages=new double[array.length-1];//Create a new array to hold the batting average values
    for(int i=0;i<battingAverages.length;i++)   //Loop through all of the averages
    {
        double average=Double.parseDouble(array[i+1]);//Convert the string object into a double
        battingAverages[i]=average; //Add the converted average to the array
    }
    System.out.print(teamName+" "+Arrays.toString(battingAverages));    //[Optional] Print out the resulting values
}