Read plain text file in Java

Posted by chrys on Fri, 27 Dec 2019 15:11:53 +0100

There seem to be many ways to read and write file data in Java.

I want to read ASCII data from a file. What are the possible methods and their differences?

#1 building

For large files, I write this code much faster:

public String readDoc(File f) {
    String text = "";
    int read, N = 1024 * 1024;
    char[] buffer = new char[N];

    try {
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);

        while(true) {
            read = br.read(buffer, 0, N);
            text += new String(buffer, 0, read);

            if(read < N) {
                break;
            }
        }
    } catch(Exception ex) {
        ex.printStackTrace();
    }

    return text;
}

#2 building

This is another way of not using external libraries:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public String readFile(String filename)
{
    String content = null;
    File file = new File(filename); // For example, foo.txt
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        content = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(reader != null){
            reader.close();
        }
    }
    return content;
}

#3 building

It may not be as fast as using buffered I / O, but it's very simple:

    String content;
    try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
        content = scanner.next();
    }

\The Z mode tells Scanner that the delimiter is EOF.

#4 building

This is a simple solution:

String content;

content = new String(Files.readAllBytes(Paths.get("sample.txt")));

#5 building

The easiest way to read data from a File in Java is to use the File class to read the File and the Scanner class to read the contents of the File.

public static void main(String args[])throws Exception
{
   File f = new File("input.txt");
   takeInputIn2DArray(f);
}

public static void takeInputIn2DArray(File f) throws Exception
{
    Scanner s = new Scanner(f);
    int a[][] = new int[20][20];
    for(int i=0; i<20; i++)
    {
        for(int j=0; j<20; j++)
        {
            a[i][j] = s.nextInt();
        }
    }
}

PS: don't forget to import java.util. *; so that the scanner can work properly.

Topics: Java ascii