Java 简明教程

Java - Files and I/O

java.io 包包含了你执行 Java 中的输入输出 (I/O) 所可能需要的几乎所有类。所有这些流都代表了一个输入源和一个输出目标。java.io 包中的流支持许多数据,比如基本类型、对象、本地化的字符等。

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.

Stream

流可以被定义为一个数据序列。流有两种:

A stream can be defined as a sequence of data. There are two kinds of Streams −

  1. InPutStream − The InputStream is used to read data from a source.

  2. OutPutStream − The OutputStream is used for writing data to a destination.

streams

Java 提供了对文件和网络的强大而灵活的 I/O 相关支持,但本教程涵盖了与流和 I/O 相关的非常基本的功能。我们一个一个地看最常用的例子:

Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O. We will see the most commonly used examples one by one −

Byte Streams

Java 字节流用于执行 8 位字节的输入和输出。虽然有许多与字节流相关的类,但最常用的类是 FileInputStreamFileOutputStream。下面是一个利用这两个类将一个输入文件复制到一个输出文件的示例:

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file −

Example

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {

   public static void main(String args[]) throws IOException {
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

现在,我们有一个文件 input.txt,其中包含以下内容:

Now let’s have a file input.txt with the following content −

This is test for copy file.

接下来,编译上述程序并执行它,这将导致创建一个内容与 input.txt 中相同的名为 output.txt 的文件。那么,我们将上述代码放入 CopyFile.java 文件中,并执行以下操作 −

As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put the above code in CopyFile.java file and do the following −

$javac CopyFile.java
$java CopyFile

Character Streams

Java Byte 流用于执行 8 位字节的输入和输出,而 Java Character 流用于执行 16 位 Unicode 的输入和输出。虽然存在许多与字符流相关的类,但最常用的类是 FileReaderFileWriter。尽管 FileReader 在内部使用 FileInputStream,FileWriter 在内部使用 FileOutputStream,但这里的主要区别在于 FileReader 一次读取两个字节,而 FileWriter 一次写入两个字节。

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

我们可重写上述示例,它利用这两个类将输入文件(包含 unicode 字符)复制到输出文件中 −

We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −

Example

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFile {

   public static void main(String args[]) throws IOException {
      FileReader in = null;
      FileWriter out = null;

      try {
         in = new FileReader("input.txt");
         out = new FileWriter("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

现在,我们有一个文件 input.txt,其中包含以下内容:

Now let’s have a file input.txt with the following content −

This is test for copy file.

接下来,编译上述程序并执行它,这将导致创建一个内容与 input.txt 中相同的名为 output.txt 的文件。那么,我们将上述代码放入 CopyFile.java 文件中,并执行以下操作 −

As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let’s put the above code in CopyFile.java file and do the following −

$javac CopyFile.java
$java CopyFile

Standard Streams

所有的编程语言都提供对标准 I/O 的支持,用户程序可从键盘获取输入,然后在计算机屏幕上生成输出。如果您知道 C 或 C++ 编程语言,那么您肯定知道三个标准设备 STDIN、STDOUT 和 STDERR。同样,Java 提供了以下三个标准流 −

All the programming languages provide support for standard I/O where the user’s program can take input from a keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streams −

  1. Standard Input − This is used to feed the data to user’s program and usually a keyboard is used as standard input stream and represented as System.in.

  2. Standard Output − This is used to output the data produced by the user’s program and usually a computer screen is used for standard output stream and represented as System.out.

  3. Standard Error − This is used to output the error data produced by the user’s program and usually a computer screen is used for standard error stream and represented as System.err.

以下是一个简单的程序,它创建 InputStreamReader 以读取标准输入流,直到用户键入“q” −

Following is a simple program, which creates InputStreamReader to read standard input stream until the user types a "q" −

Example

import java.io.InputStreamReader;
public class ReadConsole {
   public static void main(String args[]) throws IOException {
      InputStreamReader cin = null;

      try {
         cin = new InputStreamReader(System.in);
         System.out.println("Enter characters, 'q' to quit.");
         char c;
         do {
            c = (char) cin.read();
            System.out.print(c);
         } while(c != 'q');
      }finally {
         if (cin != null) {
            cin.close();
         }
      }
   }
}

我们将上述代码保存在 ReadConsole.java 文件中,并尝试编译并执行它,如下面的程序所示。此程序将继续读取并输出相同的字符,直到我们按“q”为止 −

Let’s keep the above code in ReadConsole.java file and try to compile and execute it as shown in the following program. This program continues to read and output the same character until we press 'q' −

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files

如前文所述,流可定义为数据序列。InputStream 用于从源读取数据,而 OutputStream 用于将数据写入目标。

As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

以下是对输入和输出流进行处理的类层次结构。

Here is a hierarchy of classes to deal with Input and Output streams.

file io

两个重要的流是 FileInputStreamFileOutputStream,本教程将对它们进行讨论。

The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial.

FileInputStream

此流用于从文件中读取数据。可以使用关键字 new 创建对象,并且有若干种构造函数可用。

This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

以下构造函数将文件名作为字符串以创建输入流对象来读取文件 −

Following constructor takes a file name as a string to create an input stream object to read the file −

InputStream f = new FileInputStream("C:/java/hello");

以下构造函数获取文件对象以创建输入流对象来读取文件。我们首先使用 File() 方法创建一个文件对象,如下所示 −

Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows −

File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

一旦您掌握了 InputStream 对象,即可以使用一组辅助方法来读取流或对流执行其他操作。

Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

Sr.No.

Method & Description

1

public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

2

protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

3

public int read(int r)throws IOException{} This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it’s the end of the file.

4

public int read(byte[] r) throws IOException{} This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned.

5

public int available() throws IOException{} Gives the number of bytes that can be read from this file input stream. Returns an int.

还有其他重要的输入流,有关更多详细信息,您可以参考以下链接:

There are other important input streams available, for more detail you can refer to the following links −

FileOutputStream

FileOutputStream 用于创建文件并将数据写入其中。流将在写入之前创建文件(如果尚未存在)。

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn’t already exist, before opening it for output.

下面有两个可用于创建 FileOutputStream 对象的构造函数。

Here are two constructors which can be used to create a FileOutputStream object.

下面的构造函数以字符串形式获取一个文件名,用于创建一个输入流对象以写入文件:

Following constructor takes a file name as a string to create an input stream object to write the file −

OutputStream f = new FileOutputStream("C:/java/hello")

下面的构造函数获取一个文件对象,用于创建一个输出流对象以写入文件。首先,我们使用 File() 方法创建一个文件对象,如下所示:

Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows −

File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

get OutputStream 对象后,可以使用一系列帮助方法将数据写入流或对流执行其他操作。

Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.

Sr.No.

Method & Description

1

public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

2

protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

3

public void write(int w)throws IOException{} This methods writes the specified byte to the output stream.

4

public void write(byte[] w) Writes w.length bytes from the mentioned byte array to the OutputStream.

还有其他重要输出流可用,有关更多详细信息,可以参考以下链接 −

There are other important output streams available, for more detail you can refer to the following links −

Example

以下是演示 InputStream 和 OutputStream 的示例 −

Following is the example to demonstrate InputStream and OutputStream −

import java.io.OutputStream;

public class fileStreamTest {

   public static void main(String args[]) {

      try {
         byte bWrite [] = {11,21,3,40,5};
         OutputStream os = new FileOutputStream("test.txt");
         for(int x = 0; x < bWrite.length ; x++) {
            os.write( bWrite[x] );   // writes the bytes
         }
         os.close();

         InputStream is = new FileInputStream("test.txt");
         int size = is.available();

         for(int i = 0; i < size; i++) {
            System.out.print((char)is.read() + "  ");
         }
         is.close();
      } catch (IOException e) {
         System.out.print("Exception");
      }
   }
}

上述代码将创建文件 test.txt,并以二进制格式写入给定数字。stdout 屏幕上的输出也会相同。

The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.

File Navigation and I/O

还有其他几个类我们可以接触到以了解文件导航和 I/O 的基础知识。

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.

Directories in Java

目录是一个可以包含其他文件和目录列表的文件。使用 File 对象创建目录,以列出目录中可用的文件。有关完整详细信息,请查看可以在文件对象上调用的所有方法的列表以及与目录相关的方法。

A directory is a File which can contain a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail, check a list of all the methods which you can call on File object and what are related to directories.

Creating Directories

有两个有用的 File 实用方法可用于创建目录 −

There are two useful File utility methods, which can be used to create directories −

  1. The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

  2. The mkdirs() method creates both a directory and all the parents of the directory.

以下示例创建 "/tmp/user/java/bin" 目录 −

Following example creates "/tmp/user/java/bin" directory −

Example

import java.io.File;

public class CreateDir {

   public static void main(String args[]) {
      String dirname = "/tmp/user/java/bin";
      File d = new File(dirname);

      // Create directory now.
      d.mkdirs();
   }
}

编译并执行上述代码以创建 "/tmp/user/java/bin"。

Compile and execute the above code to create "/tmp/user/java/bin".

Note − Java 会自动按照惯例处理 UNIX 和 Windows 上的路径分隔符。如果你在 Java 的 Windows 版本上使用正斜杠 (/),路径仍然会正确解析。

Note − Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Listing Directories

可以使用 File 对象提供的 list( ) 方法来列出目录中可用的所有文件和目录,如下所示 −

You can use list( ) method provided by File object to list down all the files and directories available in a directory as follows −

Example

import java.io.File;

public class ReadDir {

   public static void main(String[] args) {
      File file = null;
      String[] paths;

      try {
         // create new file object
         file = new File("/tmp");

         // array of files and directory
         paths = file.list();

         // for each name in the path array
         for(String path:paths) {
            // prints filename and directory name
            System.out.println(path);
         }
      } catch (Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

这将根据 /tmp 目录中可用的目录和文件生成以下结果 −

This will produce the following result based on the directories and files available in your /tmp directory −

Output

test1.txt
test2.txt
ReadDir.java
ReadDir.class