How do I read text data stored in a file as a string?

Asked 2 years ago, Updated 2 years ago, 129 views

I've been using the source code below. And this seems to be at least the most commonly used method on the site I searched for.

Is there another better way to read data from a file as a string from Java?

private String readFile(String file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader (file));
    String         line = null;
    StringBuilder  stringBuilder = new StringBuilder();
    String         ls = System.getProperty("line.separator");

    try {
        while((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }

        return stringBuilder.toString();
    } } finally {
        reader.close();
    }
}

java file io file-io

2022-09-22 21:28

1 Answers

Java version 7 provides an easy and powerful method using utility methods.

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

Java version 7 adds an easy way to read the text of a file called List<String> one line at a time. This method removes line delimiters and reads them one line at a time.

ist<String> lines = Files.readAllLines(Paths.get(path), encoding);

The first way to preserve line separators is to store raw file data (byte array) and decoded characters (if 8 bits are encoded in a file, the memory size is 16 bits) in memory for a short period of time, so you can temporarily require as much memory as several files.

The second way to read by line is to use memory more efficiently because the input byte buffer for decoding does not need to contain the entire document. However, it is still not suitable for very large files for available memory.

To read a large file, you need another way to read the chunk of text from the stream, process it, then move on, and reuse the same fixed-sized memory block. Here, "big" depends on the space of your computer. These days, this threshold will be about gigabytes.

One thing missing from the example of the question is character encoding. In some cases, the encoding value to be set is basically defined on the platform, but it is very rare. Therefore, developers should be able to specify and define character encoding.

The StandardChargers class defined a constant for the encoding values required in all Java running environments.

You can also use the Charset class to accept the default values for that platform.

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


2022-09-22 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.