首页 > 解决方案 > How do you create an array list of objects from a text file and have each object be an array in java?

问题描述

How would you be able to import a .txt file and then place each line into an array list as an object, but have each object be an array.

The .txt file looks like this:

1 a 1 2 
1 b 0 1 
2 a 2 3 
2 b 0 3 
3 a 3 1 
3 b 0 3 

I wanted to be able to make each line an object array like so where so that i could call upon the object and the specific point in the array:

<1,a,1,2> 
<1,b,0,1> 
<2,a,2,3> 
<2,b,0,3> 
<3,a,3,1>
<3,b,0,3> 

and then have an array list where each line (there can be any amount of line hence why i chose an array list) is one thing in the array list. kinda like <line1,line2,line3,etc..> so i can use the array list and then the values in the individual arrays within the array list.

This is the code that I currently have and i don't know where to go from here. I am using a buffered reader


        Scanner input = new Scanner(System.in);  // Create a Scanner object
        String inputString = input.nextLine(); 



        try {

            BufferedReader FSMreader = new BufferedReader(new FileReader(args[0]));      
            List<FSMline> line = new ArrayList<>(); 
            List<String> currentState = new ArrayList<>();
            List<String> inputChoice = new ArrayList<>(); 
            List<String> outputFunction = new ArrayList<>();
            List<String> nextState = new ArrayList<>();



            String lines;
            while ((lines = FSMreader.readLine()) != null) {

                line.add(new FSMline(lines.split(" ")));

            }

Any help is appreciated because i'm running out of time on a deadline in a class that i am struggling to understand.

thanks

标签: javaarraysarraylistbufferedreader

解决方案


Because you didn't mention the datatype of FSMline, I create a collection(array list of arrays) - List<String[]> - to store the content of given text file as follows:

BufferedReader fsmReader = new BufferedReader(new FileReader(args[0]));

List<String[]> contentList = new ArrayList<>();
String lines;
while ((lines = fsmReader.readLine()) != null) {
    contentList.add(lines.split(" "));
}

//print the list     
for (String[] content : contentList) {
    System.out.println(Arrays.toString(content));
}

Console output:

[1, a, 1, 2]
[1, b, 0, 1]
[2, a, 2, 3]
[2, b, 0, 3]
[3, a, 3, 1]
[3, b, 0, 3]

UPDATED

And if you want to get the third element of first array in the array list, please use get(int index) and [int index] to retrieve element from list and array, respectively:

System.out.println(contentList.get(0)[2]);

Or, you can transform an array into a list by using Arrays.asList(), then you can also use get(int index):

System.out.println(Arrays.asList(contentList.get(0)).get(2));

推荐阅读