Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java Stream, File, and IO


May 10, 2021 Java


Table of contents


Java Stream, File, and IO

Java.io package contains almost all the classes that are required for the input and output of the operation. All of these flow classes represent input sources and output targets.

Java.io in a package supports many formats, such as basic types, objects, localized character sets, and so on.

A stream can be understood as a sequence of data. The input stream represents reading data from a source, and the output stream represents writing data to a target.

Java provides I/O with powerful and flexible support for wider application in file transfer and network programming.

But this section describes the most basic and flow-related features of I/O. We'll learn about these features with an example.


Read the console input

The console input for Java is done by System.in .

To get a character stream bound to the console, you can wrap System.in in a BufferedReader object to create a character stream.

Here's the basic syntax for creating BufferedReader:

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

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


Read multi-character input from the console

Reading a character from the BufferedReader object uses the read() method, which has the following syntax:

int read() throws IOException

Each time the read() method is called, it reads a character from the input stream and returns that character as an integer value. R eturns -1 when the stream ends. This method throws IOException.

The following program demonstrates the read() method of continuously reading 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("输入字符, 按下 'q' 键退出.");
      // 读取字符
      do {
         c = (char) br.read();
         System.out.println(c);
      } while(c != 'q');
   }
}

The above examples compile and run as follows:

输入字符, 按下 'q' 键退出.
123abcq
1
2
3
a
b
c
q

Read the string from the console

Reading a string from standard input requires the ReadLine() method of BufferedReader.

Its general format is:

String readLine() throws IOException

The following program reads and displays character lines 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 above examples compile and run 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

Console output

As previously described, the output of the console is done by print() and println(). These methods are defined by the class PrintStream, and System.out is a reference to that class object.

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

PrintStream defines the simplest format for write():

void write(int byteval)

This method writes the lower eight-bit byte of byteval into the stream.

Instance

The following example outputs the character "A" and the line break immediately following to the screen with write():

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 instance to output the "A" character in the output window

A

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


Read and write the file

As mentioned earlier, a stream is defined as a data series. 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 image is a class hierarchy diagram that describes the input and output streams.

Java Stream, File, and IO

The two important streams to discuss below are FileInputStream and FileOutputStream:


FileInputStream

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

There are several construction methods that you can use to create objects.

You can use the file name of the string type 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);

By creating an InputStream object, you can read the stream or perform other stream operations using the following methods.

Serial number Method and description
1 public void close() throws IOException{}
Close this file input stream and release all system resources related to this stream. Throw an IOException exception.
2 protected void finalize()throws IOException {}
This method clears the connection to the file. M ake sure that its close method is called when the file input stream is no longer referenced. Throw an IOException exception.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream object. R eturns as an integer value. Returns the next byte of data and -1 if it is already at the end.
4 public int read(byte[] r) throws IOException{}
This method reads bytes of r.length from the input stream. R eturns the number of bytes read. If it is the end of the file, -1 is returned.
5 public int available() throws IOException{}
Returns the number of bytes that can be read from this input stream by the next method called on this input stream without blocking. Returns an integer value.

In addition to InputStream, there are a number of other input streams, with more details to refer to the following links:


FileOutputStream

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

If the stream does not exist before the file is opened for output, the stream creates the file.

There are two construction methods that you can use to create fileOutputStream objects.

Use the file name of the string type 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 a file. 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);

Once you're creating an OutputStream object, you can write to the stream or do something else using the following methods.

Serial number Method and description
1 public void close() throws IOException{}
Close this file input stream and release all system resources related to this stream. Throw an IOException exception.
2 protected void finalize()throws IOException {}
This method clears the connection to the file. M ake sure that its close method is called when the file input stream is no longer referenced. Throw an IOException exception.
3 public void write(int w)throws IOException{}
This method writes the specified bytes into the output stream.
4 public void write(byte[] w)
Write the w.length bytes in the specified array into OutputStream.

In addition to OutputStream, there are a number of other output streams, with more details to refer to the link below:

Instance

Here's an example of how InputStream and OutputStream are used:

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 a .txt test and writes the given number into the file in binary form and outputs it to the console.

Because the above code is binary write, there may be garbled code, you can use the following code instances to solve the garbled 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();
		// 关闭输入流,释放系统资源

	}
}

Files and I/O

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


The directory in Java

Create a catalog:

There are two ways to create a folder in the File class:

  • The mkdir() method creates a folder, returns true if it succeeds, and false when it fails. 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 already exist.

  • The mkdirs() method creates a folder and all of its parent folders.

The following example creates a "/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: J ava automatically distinguishes file path separators by convention in UNIX and Windows. If you use separators (/) in the Windows version of Java, the path can still be resolved correctly.


Read the directory

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

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

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

The example shown below shows how to use the list() method to check what is 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] + "是一个目录");             
            } else {
                System.out.println(s[i] + "是一个文件");
             }
        }
     } else {
          System.out.println(dirname + "不是一个目录");     }
  }
}

The above examples compile and run as follows:

目录 /tmp
bin 是一个目录
lib 是一个目录
demo 是一个目录
test.txt 是一个文件
README 是一个文件
index.html 是一个文件
include 是一个目录

Delete the directory or file

You can delete files using the java.io.File.delete() method.

The following code deletes the directory /tmp/java/, and it is important to note that when you delete a directory, you must ensure that there are no other files in the directory to be deleted correctly, otherwise the deletion will fail.

Test the directory structure:

/tmp/java/
|-- 1.log
|-- test

DeleteFileDemo .java file code:

import java.io.File;
public class DeleteFileDemo {
    public static void main(String args[]) {
        // 这里修改为自己的测试目录
        File folder = new File("/tmp/java/");
        deleteFolder(folder);
    }
    // 删除文件及目录
    public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }
}