JDK1.7 of java.nio.file.Files reads a file with only one line of code

  • 2020-11-25 07:18:00
  • OfStack

JDK 1.7 introduces a new file manipulation class, java.nio.file, which includes an Files class that contains many useful methods to manipulate files, such as checking to see if files are hidden or read-only. Developers can also read the entire file into memory using the Files.readAllBytes (Path) method, which returns a 1-byte array, and can pass the result to the String constructor to create string output. This method ensures that the resource is closed when all the byte content of the file is read in, regardless of whether an IO exception or other unchecked exception occurs. This means that you don't have to close the file after reading it to the last block. Note that this method is not suitable for reading large files because there may be a memory shortage problem. The developer should also specify the character encoding of the file to avoid any exceptions or parsing errors.

readAllBytes(Path) method source code:


<span style="font-size:32px;"> </span><span style="font-size:18px;">/** 
 * Reads all the bytes from a file. The method ensures that the file is 
 * closed when all bytes have been read or an I/O error, or other runtime 
 * exception, is thrown. 
 *  Note that this method is only suitable for simple cases where it is easy to read all the bytes in 1 A two-byte array is not suitable for reading large files  
 * <p> Note that this method is intended for simple cases where it is 
 * convenient to read all bytes into a byte array. It is not intended for 
 * reading in large files. 
 * 
 * @param  path 
 *     the path to the file 
 * 
 * @return a byte array containing the bytes read from the file 
 * 
 * @throws IOException 
 *     if an I/O error occurs reading from the stream 
 *      If it's greater than the file 2G , an out-of-memory exception will be thrown  
 * @throws OutOfMemoryError 
 *     if an array of the required size cannot be allocated, for 
 *     example the file is larger that {@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. 
 */</span><span style="font-size:18px;"> 
  public static byte[] readAllBytes(Path path) throws IOException { 
    try (SeekableByteChannel sbc = Files.newByteChannel(path); 
       InputStream in = Channels.newInputStream(sbc)) {//JDK1.7 try-with-resource 
      long size = sbc.size(); 
      if (size > (long)MAX_BUFFER_SIZE) 
        throw new OutOfMemoryError("Required array size too large"); 
 
      return read(in, (int)size); 
    } 
  }</span> 

It only takes 1 line to read the file


package entryNIO; 
 
import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
 
public class BufferAndChannel { 
  public static void main(String[] args) { 
    try { 
        System.out.println( 
         new String(Files.readAllBytes(Paths.get("C:\\FileChannelImpl.java"))) 
        ); 
       
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
} 

readAllLines method source code


public static List<String> readAllLines(Path path, Charset cs) throws IOException { 
    try (BufferedReader reader = newBufferedReader(path, cs)) { 
      List<String> result = new ArrayList<>(); 
      for (;;) { 
        String line = reader.readLine(); 
        if (line == null) 
          break; 
        result.add(line); 
      } 
      return result; 
    } 
  } 

package entryNIO; 
 
import java.util.List; 
import java.io.IOException; 
import java.nio.charset.StandardCharsets; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
 
public class BufferAndChannel { 
  public static void main(String[] args) { 
    // You can also read it this way if it's a text file   call readAllLines  methods  
    try {<span style="white-space:pre">               </span>//JDK1.8 You can leave out the control later 2 The default is UTF-8 coding  
      List<String> lines = Files.readAllLines(Paths.get("C:\\FileChannelImpl.java"), StandardCharsets.UTF_8); 
      StringBuilder sb = new StringBuilder(); 
      for (String line : lines) { 
        sb.append(line+"\n");// \r\n  A newline  
      } 
      String fromFile = sb.toString(); 
      System.out.println(fromFile); 
 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
} 

How to use Java8 streams:

First look at the source implementation


public static Stream<String> lines(Path path) throws IOException { 
    return lines(path, StandardCharsets.UTF_8); 
  } 

package entryNIO; 
 
import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
 
public class BufferAndChannel { 
  public static void main(String[] args) { 
    //Java8  new lines methods  
    try { 
       // Java8 Read files in streams, more efficiently   
      Files.lines(Paths.get(<span style="font-family: Arial, Helvetica, sans-serif;">"C:\\FileChannelImpl.java"</span>)).forEach(System.out::println);  
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
} 

It only takes 1 line to read a file and 1 line to write a file


package entryNIO; 
 
import java.util.Arrays; 
import java.util.List; 
import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.nio.file.StandardOpenOption; 
public class BufferAndChannel { 
  public static void main(String[] args){ 
    //Java8  new lines methods  
    String filePath="C:\\FileChannelImpl.java"; 
    try { 
       // Java8 Read files in streams, more efficiently   
      /*Files.lines(Paths.get(filePath)).forEach((line)->{ 
          try { 
            Files.write(Paths.get("\\1.java"), line.getBytes(), StandardOpenOption.APPEND); 
            //Files.copy(in, target, options); 
          } catch (IOException e) { 
            e.printStackTrace(); 
          } 
         
      }); */ 
       
      /* Files.readAllLines(Path path) Method returns a value of List<String> The type is theta Files.write() Designed for the  
       *  because Files.write() Need to 1 a Iterable<? extends CharSequence> Parameter of type  
       * 
       * Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) 
       */ 
      List<String> stringStream=Files.readAllLines(Paths.get(filePath)); 
      // because Files.lines(Path path) Returns the Stream<String>, So we can do it this way List<String> 
      //List<String> stringStream2=Arrays.asList((String[])Files.lines(Paths.get(filePath)).toArray()); 
       
      //StandardOpenOption For the enumeration class  , If the current Paths.get() The file does not exist, no 3 The parameters are optional StandardOpenOption.CREATE_NEW 
      // The file exists and is thrown away java.nio.file.FileAlreadyExistsException abnormal  
      Files.write(Paths.get("C:\\2.java"), stringStream, StandardOpenOption.CREATE_NEW); 
         
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
} 

Related articles: