Java 8 only needs one line of code to read a file

Source: Internet
Author: User

Java 8 only needs one line of code to read a file
Java 8 only needs to introduce a new file operation class java in one line of code JDK7. nio. file. file, which contains many useful methods to operate files, such as checking whether the File is a hidden File or whether the File is a read-only File. Developers can also use the Files. readAllBytes (Path) method to read the entire file into the memory. This method returns a byte array and passes the result to the String constructor to create String output. This method ensures that the file attribute is disabled when all the bytes of the file are read. Otherwise, an IO exception or other unchecked exceptions will occur. This means that you do not need to close the file after reading the last part of the file.
Note that this method is not suitable for reading large files because there may be insufficient memory space. Developers should also specify the character encoding of the file to avoid any exceptions or parsing errors.

Author: chszs, reprinted with note. Blog homepage: http://blog.csdn.net/chszs

If you want to read the file as a string, you can also use the readAllLines (Path path, Charset cs) method. This method is similar to the previous method, and you do not need to close the file after reading the file. However, it returns a string array instead of a byte array. Furthermore, Java 8 overrides this method and directly uses UTF-8 encoding for String Conversion without specifying character sets.
If you want to read Files in one row as strings, you can use Files. the lines () method that returns a string stream from the Read File and converts bytes into characters using UTF-8 encoding. Using the forEach () method, you can use only one line of Java code to output all the content of the file to the console, as shown in the third code snippet below.
Import java. io. IOException; import java. nio. charset. standardCharsets; import java. nio. file. files; import java. nio. file. paths; import java. util. list; public class FileReadingTest {public static void main (String [] args) throws IOException {// Java 7 example // Files. readAllBytes reads the file by default in UTF-8 encoding, so if the file encoding is not a UTF-8, then the Chinese content will appear chaotic characters System. out. println (new String (Files. readAllBytes (Paths. get ("D :\\ jd.txt"); // Java 8 example List
 
  
Lines = Files. readAllLines (Paths. get ("D: \ jd.txt"), StandardCharsets. UTF_8); StringBuilder sb = new StringBuilder (); for (String line: lines) {sb. append (line);} String fromFile = sb. toString (); System. out. println (fromFile );}}
 

If JDK 7 is not used, but JDK 8, a line of code can be used to read the file.
Import static java. lang. system. out; import static java. nio. file. files. readAllBytes; import static java. nio. file. paths. get; import java. io. IOException; public class filepattern String {public static void main (String [] args) throws IOException {// a line of code to read the file, the default is the UTF-8 encoding out. println (new String (readAllBytes (get ("d:/jd.txt "))));}}

If JDK 8 is used, you can use stream APIs to read and write files. This makes the code more concise and efficient.
In the following example, the lines () method returns the string stream, which uses UTF-8 encoding. As follows:
Import java. io. IOException; import java. nio. charset. standardCharsets; import java. nio. file. files; import java. nio. file. paths; public class Java8FileReader {public static void main (String [] args) throws IOException {// Java8 reads Files in streaming mode, making Files more efficient. lines (Paths. get ("D: \ jd.txt"), StandardCharsets. UTF_8 ). forEach (System. out: println );}}

Note the following points in the preceding example:
1) the file may be large and may exceed the memory space. Evaluate the file before use.
2) Output logs to record why the file cannot be read or any errors encountered when reading the file.
3) when converting bytes into characters, character encoding should be specified.
4) the file to be processed does not exist.

Note that if the Read File is ANSI encoded, the preceding example reports a java. nio. charset. MalformedInputException: Input length = 1 error when reading the file content.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.