How to read a text file in Java?

28

I have the file named dados.txt and I want to put it in String . For example:

String texto = lerArquivo("conteudo.txt");

Question

How to write this method lerArquivo() ?

    
asked by anonymous 10.01.2014 / 02:55

6 answers

20

The easiest way to read a file in Java, after Java 7, is through the NIO2 library. You do this with a single line of code:

String dados = new String(Files.readAllBytes(file.toPath()));

It's also the fastest way. Significantly faster than Scanner and other solutions presented. The Files class also has a method for reading row by line by saving the result in a list, and has support for different encodings.

    
10.01.2014 / 04:40
11

There are several ways to do this. Here are some:

Option 1

FileInputStream inputStream = new FileInputStream("dados.txt");
    try {
        String texto = IOUtils.toString(inputStream);
    } finally {
        inputStream.close();
    }

by @Knubo .

Option 2

Scanner in = new Scanner(new FileReader("dados.txt"));
while (in.hasNextLine()) {
    String line = scanner.nextLine();
    System.out.println(line);
}

In this way, you can read row by line.

    
10.01.2014 / 03:18
9

One way to do this is by using the standard New Input / Output 2 (NIO2) library, available from Java 7:

static String readFile(String path, Charset encoding) throws IOException 
{
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}

Usage:

String content = readFile("test.txt", StandardCharsets.UTF_8);
String content = readFile("test.txt", Charset.defaultCharset());

Source: this answer in SOEN. Note that this solution uses a considerable amount of memory, but it is simple and "safe" (ie no problems with multi-byte encodings such as UTF-8 - which would require special attention if you opt for a more efficient , such as breaking the file into chunks ). Since you intend to load the entire file into memory, I'm assuming it's fairly small.

Note also that this method preserves line breaks, ie if your file uses the standard Windows ( \r\n ), Unix ( \n ) or old Mac ( \r ), this will be kept equal in String returned. If you want to normalize line breaks, use something like Scanner - as suggested by @Calebe Oliveira - but using a StringWriter as output instead of System.out (which prints to the screen, not to a String ).

Update: as pointed out by @Elias Developer in your response, another method of class Files can be used both for encoding conversion and for breaking lines, and it supports various line, according to the documentation :

List<String> linhas = readAllLines(Paths.get("conteudo.txt"), Charset.defaultCharset());
    
10.01.2014 / 04:21
8

Just listing some other methods:

The Scanner Trick:

String texto = new Scanner(new File("dados.txt"), "UTF-8").useDelimiter("\A").next();

Guava (useful for those who still can not use Java 7) :

String texto = Files.toString(new File("dados.txt"), Charsets.UTF_8);

Commons IO - method 2 :

String texto = FileUtils.readFileToString(new File("dados.txt"), "UTF-8");

Remembering that Java 7 has the Path class and in containers Java EE is a good practice to use Class.getResourceAsStream and / or ClassLoader.getResourceAsStream to read the features of the Classpath (avoiding problems with packaging, etc.).

While there is nothing wrong with instantiating files through the File class as I did here, it is worth mentioning that there are analogous ways of reading a file to a String via InputStream , Reader , Channel URL , Path , etc (colleague @mgibsonbr for example used NIO 2 techniques involving class Paths ).

Programming for these interfaces may make it easier to reuse code. For example, if you program a method that receives a File it will only work with files; if the same method receives a InputStream you can read content from a multitude of locations (files, memory, network, etc).

I'm in the habit of writing a Util class with methods to do this type of operation over Streams and, as needed, overloading these methods to receive other more common interfaces (it's usually trivial to open a Stream from anything in Java, while the reverse is not always possible.)

Source: How to create a Java String from the contents of a file?

    
10.01.2014 / 14:27
1

Using Apache Commons IO, we can do the following:

String conteudo = IOUtils.toString(new FileInputStream("arquivo.txt"));

We can also define the charset that should be used for reading in two ways.

Method 1

String conteudo = IOUtils.toString(new FileInputStream("arquivo.txt"), Charsets.ISO_8859_1);

Method 2

String conteudo = IOUtils.toString(new FileInputStream("arquivo.txt"), "ISO-8859-1");
    
29.01.2014 / 14:02
0

I use this method:

public List<String> readFile(String fileName){

        List<String> text = new ArrayList<>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(context.getAssets().open(fileName)));
            // do reading, usually loop until end of file reading
            String mLine;
            while ((mLine = reader.readLine()) != null) {
                text.add(mLine);
                Log.i(TAG, "          line " + mLine);
            }
            Log.i(TAG,"sucess "+fileName);
        } catch (IOException e) {
            Log.i(TAG, "error " + fileName);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //log the exception
                }
            }
        }
        return text;
    }

The advantage of the other answers is that this method returns a list of text-file rows.

    
11.09.2016 / 20:00