从文件中读取并在Java中拆分数据

时间:2020-12-01 15:45:04

I'm trying to read data from a .txt file. The format looks like this:

我正在尝试从.txt文件中读取数据。格式如下:

 ABC, John, 123
 DEF, Mark, 456
 GHI, Mary, 789

I am trying to get rid of the commas and put the data into an array or structure (structure most likely).

我试图摆脱逗号并将数据放入数组或结构(结构最有可能)。

This is the code I used to to extract each item:

这是我用来提取每个项目的代码:

package prerequisiteChecker;

import java.util.*;
import java.io.*;

public class TestUnit {

    public static void main(String[]args){      
        try {
            FileInputStream fstream = new FileInputStream("courses.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            while ((strLine = br.readLine()) != null) {
                String[] splitOut = strLine.split(", ");
                for (String token : splitOut)
                    System.out.println(token);
            }
            in.close();
        } catch (Exception e){
            System.err.println("Error: " + e.getMessage());
        }
    }

} 

At one point I had a print line in the "while" loop to see if the items would be split. They were. Now I'm just at a loss on what to do next. I'm trying to place each grouping into one structure. For example: ID - ABC. First Name - John. Room - 123.

有一次,我在“while”循环中有一个打印行,看看是否会分割这些项目。他们是。现在我对下一步做什么感到茫然。我正在尝试将每个分组放入一个结构中。例如:ID - ABC。名字 - 约翰。房间 - 123。

I have a few books on Java at home and tried looking around the web. There is so much out there, and none of it seemed to lead me in the right direction.

我在家里有几本关于Java的书,并尝试在网上浏览。那里有很多东西,似乎没有一个能让我朝着正确的方向前进。

Thanks.

Michael

3 个解决方案

#1


0  

create a class that looks something like this:

创建一个看起来像这样的类:

class structure {
    public String data1;
    public String data2;
    public String data3;
}

This will form your basic data structure that you can use to hold the kind of data you have mentioned in your question. Now, you might want to follow proper object oriented methods like declaring all your fields as private, and writting getters and setters. you can find more on there here ... http://java.dzone.com/articles/getter-setter-use-or-not-use-0

这将形成您的基本数据结构,您可以使用它来保存您在问题中提到的数据类型。现在,您可能希望遵循正确的面向对象的方法,例如将所有字段声明为私有,以及写入getter和setter。你可以在这里找到更多... http://java.dzone.com/articles/getter-setter-use-or-not-use-0

Now, just outside your while loop, create an ArrayList like this: ArrayList<structure> list = new ArrayList<structure>(); This will be used to hold all the different rows of data that you will parse.

现在,在while循环之外,创建一个这样的ArrayList:ArrayList list = new ArrayList ();这将用于保存您将要解析的所有不同数据行。

Now, in your while loop do something like this:

现在,在你的while循环中执行以下操作:

structure item = new structure();//create a new instance for each row in the text file.
item.data1 = splitOut[0];
item.data2 = splitOut[1];
item.data3 = splitOut[2];
list.add(item);

this will basically take the data that you parse in each row, put in the data structure that you declared by creating a new instance of it for each new row that is parsed. this finally followed by inserting that data item in the ArrayList using the list.add(item) in the code as shown above.

这将基本上获取您在每行中解析的数据,通过为每个解析的新行创建一个新实例来声明您声明的数据结构。最后,使用代码中的list.add(item)将该数据项插入ArrayList中,如上所示。

#2


0  

I would create a nice structure to store your information. I'm not sure if how you want to access the data, but here's a nice example. I'll go off of what you previously put. Please note that I only made the variables public because they're final. They cannot change once you make the Course. If you want the course mutable, create getters and setters and change the instance variables to private. After, you can use the list to retrieve any course you'd like.

我会创建一个很好的结构来存储您的信息。我不确定您是否想要访问数据,但这是一个很好的例子。我会放弃你以前放的东西。请注意,我只是将变量公之于众,因为它们是最终的。一旦你完成课程,他们就无法改变。如果您希望课程可变,请创建getter和setter并将实例变量更改为private。之后,您可以使用该列表来检索您想要的任何课程。

package prerequisiteChecker;

import java.util.*;
import java.io.*;

public class TestUnit {

    public static void main(String[] args) {
        try {
            FileInputStream fstream = new FileInputStream("courses.txt");
                    // use DataInputStream to read binary NOT text
            // DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;
            List<Course> courses = new LinkedList<Course>();
            while ((strLine = br.readLine()) != null) {
                String[] splitOut = strLine.split(", ");
                if (splitOut.length == 3) {
                    courses.add(new Course(splitOut[0], splitOut[1],
                            splitOut[2]));
                } else {
                    System.out.println("Invalid class: " + strLine);
                }
            }
            in.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static class Course {
        public final String _id;
        public final String _name;
        public final String _room;

        public Course(String id, String name, String room) {
            _id = id;
            _name = name;
            _room = room;
        }

    }
} 

#3


0  

public class File_ReaderWriter {
    private static class Structure{
        public String data;
    }

    public static void main(String[] args) throws IOException{

        String allDataString;
        FileInputStream  fileReader = new FileInputStream ("read_data_file.txt");
        DataInputStream in = new DataInputStream(fileReader);  
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
        String[] arrayString = {"ID - ", " NAME - ", " ROOM - "};
        int recordNumber = 0;

        Structure[] structure = new Structure[10];

        for (int i = 0; i < 10; i++)
            structure[i] = new Structure();

        while((allDataString = bufferReader.readLine()) != null){
            String[] splitOut = allDataString.split(", ");
            structure[recordNumber].data = "";
            for (int i = 0; i < arrayString.length; i++){
                structure[recordNumber].data += arrayString[i] + splitOut[i];
            }
            recordNumber++;
        }

        bufferReader.close();

        for (int i = 0; i < recordNumber; i++){
                System.out.println(structure[i].data);

        }
    }


}

I modify your given code. It works. Try it and if any query then ask.

我修改你给定的代码。有用。尝试一下,如果有任何疑问,请询问。

#1


0  

create a class that looks something like this:

创建一个看起来像这样的类:

class structure {
    public String data1;
    public String data2;
    public String data3;
}

This will form your basic data structure that you can use to hold the kind of data you have mentioned in your question. Now, you might want to follow proper object oriented methods like declaring all your fields as private, and writting getters and setters. you can find more on there here ... http://java.dzone.com/articles/getter-setter-use-or-not-use-0

这将形成您的基本数据结构,您可以使用它来保存您在问题中提到的数据类型。现在,您可能希望遵循正确的面向对象的方法,例如将所有字段声明为私有,以及写入getter和setter。你可以在这里找到更多... http://java.dzone.com/articles/getter-setter-use-or-not-use-0

Now, just outside your while loop, create an ArrayList like this: ArrayList<structure> list = new ArrayList<structure>(); This will be used to hold all the different rows of data that you will parse.

现在,在while循环之外,创建一个这样的ArrayList:ArrayList list = new ArrayList ();这将用于保存您将要解析的所有不同数据行。

Now, in your while loop do something like this:

现在,在你的while循环中执行以下操作:

structure item = new structure();//create a new instance for each row in the text file.
item.data1 = splitOut[0];
item.data2 = splitOut[1];
item.data3 = splitOut[2];
list.add(item);

this will basically take the data that you parse in each row, put in the data structure that you declared by creating a new instance of it for each new row that is parsed. this finally followed by inserting that data item in the ArrayList using the list.add(item) in the code as shown above.

这将基本上获取您在每行中解析的数据,通过为每个解析的新行创建一个新实例来声明您声明的数据结构。最后,使用代码中的list.add(item)将该数据项插入ArrayList中,如上所示。

#2


0  

I would create a nice structure to store your information. I'm not sure if how you want to access the data, but here's a nice example. I'll go off of what you previously put. Please note that I only made the variables public because they're final. They cannot change once you make the Course. If you want the course mutable, create getters and setters and change the instance variables to private. After, you can use the list to retrieve any course you'd like.

我会创建一个很好的结构来存储您的信息。我不确定您是否想要访问数据,但这是一个很好的例子。我会放弃你以前放的东西。请注意,我只是将变量公之于众,因为它们是最终的。一旦你完成课程,他们就无法改变。如果您希望课程可变,请创建getter和setter并将实例变量更改为private。之后,您可以使用该列表来检索您想要的任何课程。

package prerequisiteChecker;

import java.util.*;
import java.io.*;

public class TestUnit {

    public static void main(String[] args) {
        try {
            FileInputStream fstream = new FileInputStream("courses.txt");
                    // use DataInputStream to read binary NOT text
            // DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;
            List<Course> courses = new LinkedList<Course>();
            while ((strLine = br.readLine()) != null) {
                String[] splitOut = strLine.split(", ");
                if (splitOut.length == 3) {
                    courses.add(new Course(splitOut[0], splitOut[1],
                            splitOut[2]));
                } else {
                    System.out.println("Invalid class: " + strLine);
                }
            }
            in.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static class Course {
        public final String _id;
        public final String _name;
        public final String _room;

        public Course(String id, String name, String room) {
            _id = id;
            _name = name;
            _room = room;
        }

    }
} 

#3


0  

public class File_ReaderWriter {
    private static class Structure{
        public String data;
    }

    public static void main(String[] args) throws IOException{

        String allDataString;
        FileInputStream  fileReader = new FileInputStream ("read_data_file.txt");
        DataInputStream in = new DataInputStream(fileReader);  
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
        String[] arrayString = {"ID - ", " NAME - ", " ROOM - "};
        int recordNumber = 0;

        Structure[] structure = new Structure[10];

        for (int i = 0; i < 10; i++)
            structure[i] = new Structure();

        while((allDataString = bufferReader.readLine()) != null){
            String[] splitOut = allDataString.split(", ");
            structure[recordNumber].data = "";
            for (int i = 0; i < arrayString.length; i++){
                structure[recordNumber].data += arrayString[i] + splitOut[i];
            }
            recordNumber++;
        }

        bufferReader.close();

        for (int i = 0; i < recordNumber; i++){
                System.out.println(structure[i].data);

        }
    }


}

I modify your given code. It works. Try it and if any query then ask.

我修改你给定的代码。有用。尝试一下,如果有任何疑问,请询问。