📜  Java-文件和I / O

📅  最后修改于: 2020-12-21 01:42:56             🧑  作者: Mango


java.io软件包几乎包含您可能需要用Java执行输入和输出(I / O)的每个类。所有这些流代表输入源和输出目的地。 java.io包中的流支持许多数据,例如基元,对象,本地化字符等。

流可以定义为数据序列。流有两种-

  • InPutStream -InputStream用于从源读取数据。

  • OutPutStream -OutputStream用于将数据写入目标。

流

Java为与文件和网络有关的I / O提供了强大而灵活的支持,但是本教程涵盖了与流和I / O有关的非常基本的功能。我们将一一看到最常用的示例-

字节流

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

import java.io.*;
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 ,其内容如下:

This is test for copy file.

下一步,编译上面的程序并执行它,这将导致创建output.txt文件,其内容与input.txt中的内容相同。因此,让我们将上面的代码放入CopyFile.java文件中,然后执行以下操作:

$javac CopyFile.java
$java CopyFile

字符流

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

我们可以重写上面的示例,该示例利用这两个类将输入文件(具有unicode字符)复制到输出文件中-

import java.io.*;
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 ,其内容如下:

This is test for copy file.

下一步,编译上面的程序并执行它,这将导致创建output.txt文件,其内容与input.txt中的内容相同。因此,让我们将上面的代码放入CopyFile.java文件中,然后执行以下操作:

$javac CopyFile.java
$java CopyFile

标准流

所有的编程语言都提供对标准I / O的支持,其中用户的程序可以从键盘获取输入,然后在计算机屏幕上产生输出。如果您知道C或C++编程语言,那么您必须了解三种标准设备STDIN,STDOUT和STDERR。类似地,Java提供了以下三个标准流-

  • 标准输入-用于将数据馈送到用户程序,通常将键盘用作标准输入流,并表示为System.in

  • 标准输出-用于输出用户程序产生的数据,通常计算机屏幕用于标准输出流,并表示为System.out

  • 标准错误-用于输出用户程序产生的错误数据,通常计算机屏幕用于标准错误流,并表示为System.err

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

import java.io.*;
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”-

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

读写文件

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

这是处理输入和输出流的类的层次结构。

文件IO

两个重要的流是FileInputStreamFileOutputStream ,这将在本教程中进行讨论。

FileInputStream

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

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

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

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

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

一旦有了InputStream对象,便会出现一系列帮助程序方法,可用于读取流或对该流执行其他操作。

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.

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

FileOutputStream

FileOutputStream用于创建文件并将数据写入其中。流在打开文件进行输出之前会创建一个文件(如果尚不存在)。

这是两个可用于创建FileOutputStream对象的构造函数。

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

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

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

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

一旦有了OutputStream对象,就会有一个辅助方法列表,可用于写入流或对该流执行其他操作。

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.

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

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

import java.io.*;
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并以二进制格式写入给定的数字。标准输出屏幕上的输出将相同。

文件导航和I / O

我们还将通过其他几个类来了解文件导航和I / O的基础知识。

Java目录

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

创建目录

有两种有用的File实用程序方法,可用于创建目录-

  • mkdir()方法创建一个目录,成功时返回true,失败时返回false。失败表示文件对象中指定的路径已存在,或者由于整个路径尚不存在而无法创建目录。

  • mkdirs()方法创建目录以及该目录的所有父目录。

以下示例创建“ / tmp / user / java / bin”目录-

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”。

–按照约定,Java自动处理UNIX和Windows上的路径分隔符。如果在Windows版本的Java上使用正斜杠(/),则路径仍将正确解析。

上市目录

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

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目录中可用的目录和文件产生以下结果-

输出

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