Java8 to read files using a single line of code _java

Source: Internet
Author: User

JDK7 introduces a new file action class Java.nio.file.File, which contains a number of useful ways to manipulate files, such as checking whether a file is a hidden file, or checking whether a file is a read-only file. Developers can also use the Files.readallbytes (Path) method to read the entire file into memory, this method returns a byte array, and can pass the result to a string constructor to create string output. This method ensures that when all the byte content of a file is read, the file properties are turned off, or else an IO exception or other unchecked exception occurs. This means that you do not have to close the file after reading the file to the last block content.

Note that this method is not suitable for reading large files because there may be a problem with insufficient memory space. The developer should also specify the character encoding of the file to avoid any exceptions or parse errors.

If you want to read a file as a string, you can also use the ReadAllLines (path path, Charset cs) method, which is similar to the previous method and does not need to close the file after reading the file. But it returns not a byte array, but an array of strings. Furthermore, Java8 overrides this method, eliminating the need to specify character sets and directly using UTF-8 encoding for string conversions.

If you want to read a line of text as a string, you can use the Files.lines () method, which returns a string stream from the read file and converts the bytes to characters using UTF-8 encoding. Using the foreach () method, you can output all the contents of a file to the console in just one line of Java code, such as the third code fragment below.

Copy Code code as follows:

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 {
&nbs p; //Java 7 Example
  //files.readallbytes The default UTF-8 encoding to read the file, so the file encoding if not 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<String> 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 you are not using JDK7, but JDK8, then a line of code can complete the read file.

Copy Code code as follows:

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 Fileintostring {
public static void Main (string[] args) throws IOException {
One line of code to read the file, the default is UTF-8 encoding
Out.println (New String (ReadAllBytes ("D:/jd.txt")));
}
}

If you use JDK8, you can also use the streaming APIs to read and write files so that the code is simpler and more efficient.
In the following example, the lines () method returns a string stream in which the string uses the UTF-8 encoding. As follows:

Copy Code code 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 read files in a streaming way, more efficient
Files.lines (Paths.get ("D:\\jd.txt"), Standardcharsets.utf_8). ForEach (System.out::p rintln);
}
}

The above example should note several points:

1 The file may be large, may exceed the memory space, before use to do evaluation.
2 to output the log, record why the file could not be read or any errors encountered while reading the file.
3 when converting bytes to characters, you should specify the character encoding.
4 to handle the situation where the file does not exist.

Also note that if the encoding of the read file is ANSI encoding, the example above will report java.nio.charset.MalformedInputException:Input length = 1 errors When reading the contents of the file.

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.