How to read a text file in Java?

Asked

Viewed 36,799 times

31

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

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

Question

How to write this method lerArquivo()?

6 answers

21

The easiest way to read a Java file 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 is also the fastest way. Considerably faster than the Scanner and other solutions presented. The class Files also has a method to read line by line keeping the result in a list, and supports different encodings.

  • 2

    To make the answer more complete, why not show how the method could be lerArquivo? This makes your answer more complete by answering exactly what was asked in the question. Or, if a method lerArquivo not a good idea, you can also explain why. Reference

11

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

Option 1

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

for @Knubo.

Option 2

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

This way you can read line by line.

  • If you want to save data, it would be good to opt for a database.

  • 1

    It is also good to remember that we need to pay attention to coding (encoding) file. The first option (InputStream) works only with byes, not characters (although I do not know what the IOUtils makes), and the second (FileReader) uses standard system encoding.

  • 1

    @mgibsonbr, the javadoc of IOUtils.toString(): "Get the Contents of an Inputstream as a String using the default Character encoding of the Platform."

  • 1

    Missing comment. Ioutils belongs to library Apache Commons IO

11

One way to do this is by using the standard NIO2 library (New Input/Output 2), 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();
}

Use:

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

Source: that answer in SOEN. Note that this solution uses a considerable amount of memory, but is simple and "secure" (i.e. does not present problems with multi-byte encodings such as UTF-8 - which would require special attention if you chose a more efficient strategy, such as breaking the file in Chunks). As you intend to load the entire file in memory, I am assuming that it is fairly small.

Note also that this method preserves line breaks, i.e. if your file uses the default Windows (\r\n), Unix (\n) or old Mac (\r), this will be kept equal in the 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 (that prints to the screen, and not to a String).

Updating: as pointed out by @Elias Developer in his reply, another class method Files can be used both for conversion of encoding as for line breaks, and that supports several types of line breaks, according to the documentation:

List<String> linhas = readAllLines(Paths.get("conteudo.txt"), Charset.defaultCharset());

11

Just Listing Some Other Methods:

Class Files in Java 11+ (recommended)

String texto = Files.readString(Path.get("dados.txt"), StandardCharsets.UTF_8); 

The Trick of the Scanner:

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

Guava (useful for those who cannot yet 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 class Path and in containers Java EE is good practice using methods Class.getResourceAsStream and / or ClassLoader.getResourceAsStream to read the resources of Classpath (avoiding problems with packaging, etc).

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

Programming for these interfaces can facilitate code reuse. 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 have a habit of writing a class Util with methods to do this type of operation on top of Streams and, as necessary, overload these methods to receive other more common interfaces (in general it is trivial to open a Stream from anything in Java, while the opposite is not always possible) .

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

1

Using Apache Commons IO, we can do it as follows:

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

We can also define the charset which 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");

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 lines.

Browser other questions tagged

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