Read . txt files and put them in an Arraylist

Asked

Viewed 3,282 times

-1

How to read the file . txt below and turn it into an Arraylist?

Alicate;6;3.4

Martelo;10;4.5

The Arraylist at the end would look like this: [[Pliers, 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!");}
    }
  • To stay this way only using one Arraylist inside another. ArrayList<ArrayList<String>> list2 = new ArrayList<>();. Depending on what you want, maybe another solution is better.

  • If each row is a product, the best solution is to create a class for it and as you read the file elements create class objects with the respective row information.

2 answers

3


1

The String class has the method split(String regex), that breaks a String into an array taking as 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. Thus, you can do so to create a list that contains the elements of an array:

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

Looking at the method backwards, you first split the String into an array using ";" as the separator character, then convert that array into a list, and finally store that list into a variable called an example.

For its specific need, the idea would be to have a list that stores String arrays. By reading each line and using the split method, you would add the return of this method to this created list. After reading the file, just print out this list. It would be 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)));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.