简体   繁体   English

用于读取文本文件和创建对象的Java程序

[英]Java program for reading a text file and creating objects

I am currently writing a program to read in data from a text file and utilize the data in some way. 我目前正在编写一个程序,以从文本文件中读取数据并以某种方式利用数据。 So far I can read the file no problem but the issue I am having is with what comes next. 到目前为止,我可以读取文件没有问题,但是接下来的问题是我遇到的问题。 As the data is read from the text file the appropriate objects must be created, from classes that I have already built, and stored in 2 arrays based upon the data. 从文本文件中读取数据时,必须从我已经构建的类中创建适当的对象,并根据数据将其存储在2个数组中。 As I said before I have the code for the data to be read completed but I do not know how to use that data to create objects and to store those objects into arrays. 就像我之前说过的那样,我已经完成了要读取的数据的代码,但是我不知道如何使用该数据来创建对象并将这些对象存储到数组中。

Here is the code that I have so far in the main method: 这是到目前为止我在main方法中拥有的代码:

public static void main(String[] args) {
        BufferedReader inputStream = null;

        String fileLine;
        try {
            inputStream = new BufferedReader(new FileReader("EmployeeData.txt"));

            System.out.println("Employee Data:");
            // Read one Line using BufferedReader
            while ((fileLine = inputStream.readLine()) != null) {
                System.out.println(fileLine);
            }//end while
        } catch (IOException io) {
            System.out.println("File IO exception" + io.getMessage());
        }finally {
            // Need another catch for closing 
            // the streams          
            try {               
                if (inputStream != null) {
                inputStream.close();
            }                
            } catch (IOException io) {
                System.out.println("Issue closing the Files" + io.getMessage());
            }//end catch
        }//end finally
    }//end main method

You have to think about how data are represented in the text file and map them accordingly to the Employee class. 您必须考虑数据如何在文本文件中表示,并将它们相应地映射到Employee类。

Take for instance if the Employee class is as below - Employee类如下所示为例-

class Employee {
   String firstName;
   String lastName;

}

and the lines in the file are like - 文件中的行就像-

first1 last1
first2 last2

You can create an arrayList of Employee to hold the data - 您可以创建EmployeearrayList来保存数据-

List<Employee> employees = new ArrayList();

When you read each line from the file, you can split the line by space, construct the object and add to the list - 从文件中读取每一行时,您可以按行将行分开,构造对象并添加到列表中-

String[] name = fileLine.split(" ");
Employee e = new Employee();
e.firstName = name[0];
e.lastName = name[1];

employees.add(e);

So basically, you have to consider the structure of the data in your source (text file) and figure out how you would parse them and construct your desired object. 因此,基本上,您必须考虑源(文本文件)中数据的结构,并弄清楚如何解析它们并构造所需的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM