简体   繁体   中英

java i/o read in multi line file and store as arraylist

I want to read in a simple text file and save it as an ArrayList. The file looks like so

0.2253 
0.808 
0.132 
0.341 

4.18546
8.65418
1.45535
0.341

and so on...

They will always be four lines and they will always be delimited by a blank space. Somehow I'd like to use that as the break point to begin the new array and pick back up with the first new number as index zero.

The numbers must be stored as strings.

I want to assign this data to an ArrayList such that

[0][0] = 0.2253
[0][1] = 0.808
[0][2] = 0.132
[0][3] = 0.341

[1][0] = 4.18546
[1][1] = 8.65418
[1][2] = 1.45535
[1][3] = 0.341

how can I do this using the structures of java i/o?

java io arraylist

So far I have this..

    //array list data struc
    ArrayList<String> array_list = new ArrayList<String>();

    String component_doc = "/home/joao/document.txt"

    Scanner inFile = null;
    try 
    {
        inFile = new Scanner(new File(component_doc));
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }

    while(inFile.hasNextLine())
    {
        array_list.add(inFile.nextLine());
    }

This is a way to read in those lines and put them in an array list.

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

protected static ArrayList<String> yourArrayList = new ArrayList<String>();
String fileName = "C:\\Users\\myComputer\\Desktop\\test_file.txt";
    try
    {
        List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
        for (int i = 0; i < lines.size(); i++)
        {
            yourArrayList.add(lines.get(i).toString());
        }
    }catch(IOException io)
    {
        io.printStackTrace();
    }

Just a hint:

ArrayList<ArrayList<String>> array_list = new ArrayList<ArrayList<String>>(); //Create 2D arrayList

// open file and do all previous stuff 

ArrayList<String> item = new ArrayList<String>(); // Create 1D ArrayList 

while(inFile.hasNextLine())
     String str = nextLine(); 
     if (str.trim().length() == 0) {  // is blank line?
         if (item.size() > 0) array_list.add(item); // Store 1D arrayList into 2D 
         item = new ArrayList<String>();  // Create new 1D arrayList
     }
     else { 
          item.add(strLine); // Add each element to 1D arrayList
     } 
} 

Remark : This is an instance of an ArrayList , so you can't access them using array_list[X][Y] . You could try the method .toArray() to convert it to a true 2-D array.

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