Read .txt files and put them in an ArrayList

-1

How do I read the .txt file below and turn it into an ArrayList?

Alicate;6;3.4

Martelo;10;4.5

The ArrayList in the end would look like this: [[6, 3.4], [Hammer, 10; 4.5], ...]

try{

            FileReader fr = new FileReader("ferramentas.txt");
            BufferedReader br = new BufferedReader(fr);

            String str;
            while((str = br.readLine()) != null){
                out.println(str + "\n");
            } 

        }
        catch(IOException e){
        out.println("Arquivo não encontrado!");}
    }
    
asked by anonymous 16.01.2018 / 15:28

2 answers

2

You can use the Files#readAllLines() :

Path path = Paths.get("C:", "ferramentas.txt"); // C:\ferramentas.txt
List<String> linhas = Files.readAllLines(path);

Running on Repl.it

    
16.01.2018 / 18:02
0

The String class has the method split (String regex) , which breaks a String in an array by taking as a parameter a character that repeats itself within that String. This array will then contain all the elements that in their original String were separated by ; .

In your case, you have ; as a repeater character. This way, you can do this to create a list that contains the elements of an array:

List<String> exemplo = Arrays.asList(str.split(";"));

Observing the method backwards, you first split the String into an array using the ";" as a separator, then converts that array to a list and finally stores that list in a variable named example.

For your specific needs, the idea is to have a list that stores String arrays. When reading each line and using the split method, you would add the return of that method to that created list. After reading the entire file, just print this list. It would look something like this:

    List<String[]> lista = new ArrayList<>();    
    try {

            FileReader fr = new FileReader("ferramentas.txt");
            BufferedReader br = new BufferedReader(fr);

            String str;
            while((str = br.readLine()) != null){
                lista.add(str.split(";"))
            } 

     } catch(IOException e) {
           out.println("Arquivo não encontrado!");
     } finally {
         br.close(); 
     }

     lista.forEach(a -> System.out.println(Arrays.toString(a)));
    
16.01.2018 / 17:02