简体   繁体   中英

Reading from file and splitting the data in Java

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

 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.

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.

Thanks.

Michael

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

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.

Now, in your while loop do something like this:

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.

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.

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;
        }

    }
} 
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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