Whole text file to a String in Java

2019-01-07 20:10发布

Does Java has a one line instruction to read to a text file, like what C# has?

I mean, is there something equivalent to this in Java?:

String data = System.IO.File.ReadAllText("path to file");

If not... what is the 'optimal way' to do this...?

Edit:
I prefer a way within Java standard libraries... I can not use 3rd party libraries..

9条回答
冷血范
2楼-- · 2019-01-07 20:49

Java 7 improves on this sorry state of affairs with the Files class (not to be confused with Guava's class of the same name), you can get all lines from a file - without external libraries - with:

List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);

Or into one String:

String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));

If you need something out of the box with a clean JDK this works great. That said, why are you writing Java without Guava?

查看更多
在下西门庆
3楼-- · 2019-01-07 20:54

In Java 8 (no external libraries) you could use streams. This code reads a file and puts all lines separated by ', ' into a String.

try (Stream<String> lines = Files.lines(myPath)) {
    list = lines.collect(Collectors.joining(", "));
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}
查看更多
戒情不戒烟
4楼-- · 2019-01-07 20:55

AFAIK, there is no one-liner with standard libraries. Typical approach with standard libraries would be something like this:

public static String readStream(InputStream is) {
    StringBuilder sb = new StringBuilder(512);
    try {
        Reader r = new InputStreamReader(is, "UTF-8");
        int c = 0;
        while ((c = r.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}

Notes:

  • in order to read text from file, use FileInputStream
  • if performance is important and you are reading large files, it would be advisable to wrap the stream in BufferedInputStream
  • the stream should be closed by the caller
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-07 21:00

Not within the main Java libraries, but you can use Guava:

String data = Files.asCharSource(new File("path.txt"), Charsets.UTF_8).read();

Or to read lines:

List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );

Of course I'm sure there are other 3rd party libraries which would make it similarly easy - I'm just most familiar with Guava.

查看更多
趁早两清
6楼-- · 2019-01-07 21:06

No external libraries needed. The content of the file will be buffered before converting to string.

Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
查看更多
Ridiculous、
7楼-- · 2019-01-07 21:06

No external libraries needed. The content of the file will be buffered before converting to string.

  String fileContent="";
  try {
          File f = new File("path2file");
          byte[] bf = new byte[(int)f.length()];
          new FileInputStream(f).read(bf);
          fileContent = new String(bf, "UTF-8");
      } catch (FileNotFoundException e) {
          // handle file not found exception
      } catch (IOException e) {
          // handle IO-exception
      }
查看更多
登录 后发表回答