Java Nio 简明教程

Java NIO - File

Java NIO 包提供了另一个实用程序 API 名为 Files,它基本上用于使用其主要用于 Path 对象的静态方法操作文件和目录。

Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object.

如 Path 教程中所述,Path 接口是在 Java 7 版本的文件包中引入 Java NIO 包的。因此,此教程适用于相同的文件包。

As mentioned in Path tutorial that Path interface is introduced in Java NIO package during Java 7 version in file package.So this tutorial is for same File package.

此类完全包含对文件、目录或其他类型文件进行操作的静态方法。在大多数情况下,此处定义的方法会委托给关联的文件系统提供程序以执行文件操作。

This class consists exclusively of static methods that operate on files, directories, or other types of files.In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

在 Files 类中定义了许多方法,也可以从 Java 文档中读取这些方法。在本教程中,我们尝试涵盖 Java NIO Files 类所有方法中的一些重要方法。

There are many methods defined in the Files class which could also be read from Java docs.In this tutorial we tried to cover some of the important methods among all of the methods of Java NIO Files class.

Important methods of Files class.

以下是 Java NIO Files 类中定义的重要方法。

Following are the important methods defined in Java NIO Files class.

  1. createFile(Path filePath, FileAttribute attrs) − Files class provides this method to create file using specified Path.

Example

package com.java.nio;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
   public static void main(String[] args) {
      //initialize Path object
      Path path = Paths.get("D:file.txt");
      //create file
      try {
         Path createdFilePath = Files.createFile(path);
         System.out.println("Created a file at : "+createdFilePath);
      }
      catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Created a file at : D:\data\file.txt
  1. copy(InputStream in, Path target, CopyOption� options) − This method is used to copies all bytes from specified input stream to specified target file and returns number of bytes read or written as long value.LinkOption for this parameter with the following values −

Example

package com.java.nio;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
public class WriteFile {
   public static void main(String[] args) {
      Path sourceFile = Paths.get("D:file.txt");
      Path targetFile = Paths.get("D:fileCopy.txt");
      try {
         Files.copy(sourceFile, targetFile,
         StandardCopyOption.REPLACE_EXISTING);
      }
      catch (IOException ex) {
         System.err.format("I/O Error when copying file");
      }
      Path wiki_path = Paths.get("D:fileCopy.txt");
      Charset charset = Charset.forName("ISO-8859-1");
      try {
         List<String> lines = Files.readAllLines(wiki_path, charset);
         for (String line : lines) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

Output

To be or not to be?
  1. createDirectories(Path dir, FileAttribute<?>…​attrs) − This method is used to create directories using given path by creating all nonexistent parent directories.

  2. delete(Path path) − This method is used to deletes the file from specified path.It throws NoSuchFileException if the file is not exists at specified path or if the file is directory and it may not empty and cannot be deleted.

  3. exists(Path path) − This method is used to check if file exists at specified path and if the file exists it will return true or else it returns false.

  4. readAllBytes(Path path) − This method is used to reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file.

Example

package com.java.nio;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class ReadFile {
   public static void main(String[] args) {
      Path wiki_path = Paths.get("D:file.txt");
      Charset charset = Charset.forName("ISO-8859-1");
      try {
         List<String> lines = Files.readAllLines(wiki_path, charset);
         for (String line : lines) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

Output

Welcome to file.
  1. size(Path path) − This method is used to get the size of the file at specified path in bytes.

  2. write(Path path, byte[] bytes, OpenOption� options) − This method is used to writes bytes to a file at specified path.

Example

package com.java.nio;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class WriteFile {
   public static void main(String[] args) {
      Path path = Paths.get("D:file.txt");
      String question = "To be or not to be?";
      Charset charset = Charset.forName("ISO-8859-1");
      try {
         Files.write(path, question.getBytes());
         List<String> lines = Files.readAllLines(path, charset);
         for (String line : lines) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

Output

To be or not to be?