Whole text file to a String in Java

后端 未结 10 2266
遇见更好的自我
遇见更好的自我 2020-12-01 15:44

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 =          


        
10条回答
  •  心在旅途
    2020-12-01 16:18

    With JDK/11, you can read a complete file at a Path as a string using Files.readString(Path path):

    try {
        String fileContent = Files.readString(Path.of("/foo/bar/gus"));
    } catch (IOException e) {
        // handle exception in i/o
    }
    

    the method documentation from the JDK reads as follows:

    /**
     * Reads all content from a file into a string, decoding from bytes to characters
     * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
     * The method ensures that the file is closed when all content have been read
     * or an I/O error, or other runtime exception, is thrown.
     *
     * 

    This method is equivalent to: * {@code readString(path, StandardCharsets.UTF_8) } * * @param path the path to the file * * @return a String containing the content read from the file * * @throws IOException * if an I/O error occurs reading from the file or a malformed or * unmappable byte sequence is read * @throws OutOfMemoryError * if the file is extremely large, for example larger than {@code 2GB} * @throws SecurityException * In the case of the default provider, and a security manager is * installed, the {@link SecurityManager#checkRead(String) checkRead} * method is invoked to check read access to the file. * * @since 11 */ public static String readString(Path path) throws IOException

提交回复
热议问题