How to read data from txt files using Java?

4

Is there a mechanism for storing the data of a .txt file in a LinkedList? For example, how would this list have the Strings "Caio", "Peter" and "Luiza" as elements?

import java.io.*;

public class teste {
    public static void main ( String args [] ) throws IOException {
        LinkedList<String> linkedlist = new LinkedList<String>(); /*lista de Strings*/

        File arquivo = new File("C:\NetBeans\teste.txt");
        arquivo.createNewFile();
        FileWriter fw = new FileWriter(arquivo, true);
        BufferedWriter bw = new BufferedWriter(fw);

        bw.write("Caio Pedro Luiza");
        bw.close();
        fw.close();
    }
}
    
asked by anonymous 15.07.2015 / 22:20

2 answers

3

Alternatively, you can use FileUtils available at Apache Commons IO :

import java.util.Arrays;
import org.apache.commons.io.FileUtils;
(...)

// é fundamental definir o charset do arquivo
String conteudo = FileUtils.readFileToString("E:\teste.txt", "UTF-8");
List<String> listaNomes = Arrays.asList(conteudo.split(" "));
System.out.println("Conteudo lista" + listaNomes);

If possible, separate the names in the file per line instead of space (hence you can use full names). It would look like this:

List<String> listaNomes = FileUtils.readLines("E:\teste.txt", "UTF-8");
System.out.println("Conteudo lista" + listaNomes);

Unless you have some restriction on adding dependencies in your project.

    
16.07.2015 / 22:36
5

poirot , you can do this:

public class Testes {

    public static void main(String[] args) throws IOException {
        File arquivo = new File("E:\teste.txt");
        arquivo.createNewFile();
        FileWriter fw = new FileWriter(arquivo, true);
        BufferedWriter bw = new BufferedWriter(fw);

        bw.write("Caio Pedro Luiza");
        bw.close();
        fw.close();

        LinkedList<String> listaNomes = new LinkedList<String>();
        Scanner in = new Scanner(new FileReader("E:\teste.txt"));

        while (in.hasNextLine()) 
        {
            String line = in.nextLine();
            System.out.println(line);
            String array[] = line.split(" ");

            for (String i : array) 
            {
                listaNomes.add(i);
            }
            System.out.println("Conteudo lista" + listaNomes);
        }

    }

}

Output:

  

Content list [Caio, Pedro, Luiza]

Note : Do not need to be LinkedList , could be any other type of lista even a common% co_.     

16.07.2015 / 00:32