Java Stream、File、IO


The Java.io package contains almost all classes needed to operate input and output. All these stream classes represent input sources and output destinations.

The streams in the Java.io package support many formats, such as basic types, objects, localized character sets, etc.

A stream can be understood as a sequence of data. An input stream represents reading data from a source, and an output stream represents writing data to a destination.

Java provides powerful and flexible support for I/O, making it more widely used in file transfer and network programming.

But this section describes the most basic functions related to streams and I/O. We will learn these functions through examples one by one.


Read console input

Java's console input is completed by System.in.

To obtain a character stream bound to the console, you can create a character stream by wrapping System.in in a BufferedReader object.

The following is the basic syntax for creating a BufferedReader:

BufferedReader br = new BufferedReader(new 
                      InputStreamReader(System.in));

After the BufferedReader object is created, we can use the read() method to read a character from the console, or use the readLine() method to read a string.


Read multi-character input from the console

To read a character from the BufferedReader object, use the read() method. Its syntax is as follows:

int read( ) throws IOException

Every When the read() method is called, it reads a character from the input stream and returns the character as an integer value. Returns -1 when the stream ends. This method throws IOException.

The following program demonstrates using the read() method to continuously read characters from the console until the user enters "q".

// 使用 BufferedReader 在控制台读取字符

import java.io.*;

public class BRRead {
   public static void main(String args[]) throws IOException
   {
      char c;
      // 使用 System.in 创建 BufferedReader 
      BufferedReader br = new BufferedReader(new 
                         InputStreamReader(System.in));
      System.out.println("Enter characters, 'q' to quit.");
      // 读取字符
      do {
         c = (char) br.read();
         System.out.println(c);
      } while(c != 'q');
   }
}

The compilation and running results of the above example are as follows:

Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q

Reading a string from the console

To read a string from the standard input, you need to use the readLine of BufferedReader ()method.

Its general format is:

String readLine( ) throws IOException

The following program reads and displays lines of characters until you enter the word "end".

// 使用 BufferedReader 在控制台读取字符
import java.io.*;
public class BRReadLines {
   public static void main(String args[]) throws IOException
   {
      // 使用 System.in 创建 BufferedReader 
      BufferedReader br = new BufferedReader(new
                              InputStreamReader(System.in));
      String str;
      System.out.println("Enter lines of text.");
      System.out.println("Enter 'end' to quit.");
      do {
         str = br.readLine();
         System.out.println(str);
      } while(!str.equals("end"));
   }
}

The compilation and running results of the above examples are as follows:

Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end

In versions after JDK 5, we can also use the Java Scanner class to obtain console input.

Console output

As mentioned before, console output is completed by print() and println(). These methods are defined by the PrintStream class, and System.out is a reference to the object of this class.

PrintStream inherits the OutputStream class and implements the method write(). In this way, write() can also be used to write operations to the console.

PrintStream The simplest form of defining write() is as follows:

void write(int byteval)

This method writes the lower octet of byteval to the stream.

Example

The following example uses write() to output the character "A" and the following newline character to the screen:

import java.io.*;

// 演示 System.out.write().
public class WriteDemo {
   public static void main(String args[]) {
      int b; 
      b = 'A';
      System.out.write(b);
      System.out.write('\n');
   }
}

Run the above example to output in the output window "A" character

A

Note: The write() method is not often used because the print() and println() methods are more convenient to use.


Reading and writing files

As mentioned earlier, a stream is defined as a sequence of data. The input stream is used to read data from the source, and the output stream is used to write data to the target.

The following figure is a class hierarchy diagram describing the input stream and output stream.

12-130Q122402I57.jpg

The two important streams to be discussed below are FileInputStream and FileOutputStream:


FileInputStream

This stream is used to read data from a file , its objects can be created using the keyword new.

There are various construction methods that can be used to create objects.

You can use a string type file name to create an input stream object to read the file:

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

You can also use a file object to create an input stream object to read the file. We first have to use the File() method to create a file object:

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

After creating the InputStream object, you can use the following methods to read the stream or perform other stream operations.

Serial numberMethod and description
1 public void close() throws IOException{}
Close this file input stream and release all system resources related to this stream. Throws IOException.
2protected void finalize()throws IOException {}
This method clears the connection to the file. Make sure to call the file input stream's close method when it is no longer referenced. Throws IOException.
3public int read(int r)throws IOException{}
This method reads the specified bytes from the InputStream object data. Returned as an integer value. Returns the next byte of data, or -1 if the end has been reached.
4public int read(byte[] r) throws IOException{}
This method reads r from the input stream. length in bytes. Returns the number of bytes read. If it is the end of the file, -1 is returned.
5public int available() throws IOException{}
The method returned next time this input stream is called can be ignored The number of bytes to read blockingly from this input stream. Returns an integer value.

In addition to InputStream, there are some other input streams. For more details, please refer to the link below:

  • ByteArrayInputStream

  • DataInputStream


FileOutputStream

This class is used to create a file and write data to the file.

If the target file does not exist before the stream opens the file for output, then the stream will create the file.

There are two constructors that can be used to create FileOutputStream objects.

Use a string type file name to create an output stream object:

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

You can also use a file object to create an output stream to write files. We first have to use the File() method to create a file object:

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

After creating the OutputStream object, you can use the following methods to write to the stream or perform other stream operations.

Serial numberMethod and description
1 public void close() throws IOException{}
Close this file input stream and release all system resources related to this stream. Throws IOException.
2protected void finalize()throws IOException {}
This method clears the connection to the file. Make sure to call the file input stream's close method when it is no longer referenced. Throws IOException.
3public void write(int w)throws IOException{}
This method writes the specified bytes to the output stream middle.
4public void write(byte[] w)
Write the bytes of length w.length in the specified array to OutputStream.

In addition to OutputStream, there are some other output streams. For more details, please refer to the link below:

  • ByteArrayOutputStream

  • DataOutputStream

Example

The following is an example demonstrating the usage of InputStream and 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");
   }	
   }
}

The above program first creates the file test.txt and puts the given The numbers are written into the file in binary form and output to the console at the same time.

Because the above code is written in binary, there may be garbled characters. You can use the following code examples to solve the garbled code problem:

//文件名 :fileStreamTest2.java
import java.io.*;

public class fileStreamTest2{
	public static void main(String[] args) throws IOException {
		
		File f = new File("a.txt");
		FileOutputStream fop = new FileOutputStream(f);
		// 构建FileOutputStream对象,文件不存在会自动新建
		
		OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
		// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
		
		writer.append("中文输入");
		// 写入到缓冲区
		
		writer.append("\r\n");
		//换行
		
		writer.append("English");
		// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
		
		writer.close();
		//关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
		
		fop.close();
		// 关闭输出流,释放系统资源

		FileInputStream fip = new FileInputStream(f);
		// 构建FileInputStream对象
		
		InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
		// 构建InputStreamReader对象,编码与写入相同

		StringBuffer sb = new StringBuffer();
		while (reader.ready()) {
			sb.append((char) reader.read());
			// 转成char加到StringBuffer对象中
		}
		System.out.println(sb.toString());
		reader.close();
		// 关闭读取流
		
		fip.close();
		// 关闭输入流,释放系统资源

	}
}

File and I/O

There are also some classes about files and I/O that we also need to know:

  • File Class(Class)

  • FileReader Class(Class )

  • FileWriter Class(Class)


Directory in Java

Create directory:

There are two methods in the File class that can be used to create folders:

  • mkdir( )The method creates a folder and returns true if successful, otherwise Return false. Failure indicates that the path specified by the File object already exists, or that the folder cannot be created because the entire path does not yet exist.

  • mkdirs()Method creates a folder and all its parent folders.

The following example creates the "/tmp/user/java/bin" folder:

import java.io.File;

public class CreateDir {
   public static void main(String args[]) {
      String dirname = "/tmp/user/java/bin";
      File d = new File(dirname);
      // 现在创建目录
      d.mkdirs();
  }
}

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

Note: Java automatically distinguishes file path separators by convention on UNIX and Windows. If you use the separator (/) in the Windows version of Java, the path will still be parsed correctly.


Read directory

A directory is actually a File object, which contains other files and folders.

If you create a File object and it is a directory, calling the isDirectory() method will return true.

You can extract the list of files and folders it contains by calling the list() method on the object.

The example shown below illustrates how to use the list() method to check the contents contained in a folder:

import java.io.File;

public class DirList {
   public static void main(String args[]) {
      String dirname = "/tmp";
      File f1 = new File(dirname);
      if (f1.isDirectory()) {
         System.out.println( "Directory of " + dirname);
         String s[] = f1.list();
         for (int i=0; i < s.length; i++) {
            File f = new File(dirname + "/" + s[i]);
            if (f.isDirectory()) {
               System.out.println(s[i] + " is a directory");
            } else {
               System.out.println(s[i] + " is a file");
            }
         }
      } else {
         System.out.println(dirname + " is not a directory");
    }
  }
}

The compilation and running results of the above example are as follows:

Directory of /tmp
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory