JDK1.7 introduces the new file operation class java.nio.file package. There is a Files class that contains many useful methods to operate files, such as checking whether the file is a hidden file, or checking whether the 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 also pass the result to the String constructor to create string output. This method ensures that when all byte contents of the file are read, the resource is closed regardless of whether there is an IO exception or other unchecked exception. This means that after reading the file to the last block content, there is no need to close 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.
The source code of readAllBytes(Path) method:
<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 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 greater than 2G of the file, a memory overflow 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>Only one line of the file is read
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(); } } }The source code of readAllLines method
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) { //If it is a text file, you can also read it like this. Call the readAllLines method try {<span style="white-space:pre"> </span>//The second parameter can be omitted after JDK1.8. The default is UTF-8 encoding 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 Newline} String fromFile = sb.toString(); System.out.println(fromFile); } catch (IOException e) { e.printStackTrace(); } } }How to use Java8 streams:
First look at the source code 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 adds lines method try { // Java8 uses streaming to read files, making it more efficient 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(); } } }Only one line is required to read a file and 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 adds the lines method String filePath="C://FileChannelImpl.java"; try { // Java8 reads files in a stream, which is more efficient/*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 the value of the List<String> type, which is designed for Files.write()* Because Files.write() needs to pass in a parameter of Iterable<? extends CharSequence> 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 Stream<String>, you can use the following method to become List<String> //List<String> stringStream2=Arrays.asList((String[])Files.lines(Paths.get(filePath)).toArray()); //StandardOpenOption is an enumeration class. If the file currently Paths.get() does not exist, the third parameter can be selected as StandardOpenOption.CREATE_NEW // If the file exists, throw java.nio.file.FileAlreadyExistsException exception Files.write(Paths.get("C://2.java"), stringStream, StandardOpenOption.CREATE_NEW); } catch (IOException e) { e.printStackTrace(); } } }The above article JDK1.7 java.nio.file.Files only requires one line of code to realize the above file. This is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.