Problem solving chapter09

subject

  1. What are the classifications of streams in Java?
  2. What are the subclasses of byte stream InputStream and OutputStream? Please give an example to illustrate its usage scenario. What are the corresponding character streams?
  3. What is the conversion between byte stream and character stream? What support does Java provide for this?
  4. What is the role of filtering streams (assembly of streams) in Java? Please give an example of a commonly used filter stream.
  5. What is serialization and deserialization of objects? What support does Java provide for this?
  6. What does the Java File class represent? What does it do?
  7. What support does Java provide for reading and writing files?

1. What are the classifications of streams in Java?

  • From the direction of flow: it is generally divided into input stream and output stream. From the perspective of reading type, it is generally divided into byte stream and character stream. Byte stream is a series of classes derived from InputStream and OutputStream, with bytes as the processing unit; Character stream is a series of classes derived from Reader and Writer. The processing unit is the character represented by 16 bit Unicode code.

2. What are the subclasses of byte stream InputStream and OutputStream? Please give an example to illustrate its usage scenario. What are the corresponding character streams?

  • Byte stream InputStream:

java.io.InputStream

java.io.FileInputStream / / file input stream, corresponding to Java io. InputstreamReader
java.io.PipedInputStream / / pipeline input stream, corresponding to Java io. Pipedreader
java.io.ObjectInputStream / / object input stream, used to serialize problems
java.io.ByteArrayInputStream / / byte input stream, corresponding to Java io. CharArrayReader
java.io.SequenceInputStream / / sequence input stream

java.io.FilterInputStream / / the filtered input stream contains some other input streams. It is used as its basic data source. It may convert data along the way or provide other functions.
java.io.DataInputStream
java.io.BufferedInputStream
java.io.PushbackInputStream

  • Byte stream OutputStream:

java.io.OutputStream

java.io.FileOutputStream / / file output stream, corresponding to Java io. FileReader
java.io.PipedOutputStream / / pipeline output stream, corresponding to Java io. PipedReader
java.io.ObjectOutputStream / / object output stream
java.io.ByteArrayOutputStream / / byte output stream, corresponding to Java io. CharReader
java.io.FilterOutputStream / / filter the output stream

java.io.DataOutputStream
java.io.BufferedOutputStream
java.io.PrintStream

3. What is the conversion between byte stream and character stream? What support does Java provide for this?

The input byte stream sometimes needs to be converted into character stream, and the output character stream sometimes needs to be converted into byte stream. The conversion process is also called the assembly process of stream. The method of conversion is:
(1) The construction method of InputStreamReader is required to convert input bytes into character streams:
InputStreamReader(InputStream in)
Its use method is:
InputStreamReader ins = new InputStreamReader(new FileInputStream("c:\\text.txt") ) ;
After that, the text file can be read from the character point of view through the ins method txt.
(2) The construction method of OutputStreamWriter or PrintWriter is used to transfer output characters to byte stream:
OutputStreamWriter(OutputStream out)PrintWriter(OutputStream out);
Its use method is:
OutputStreamWriter outs = new OutputStreamWriter(new FileOutputStream("c:\\text.txt") );
After that, you can directly output characters to text through outs Txt file.
This transformation process does not change the content of the flow, but changes the perspective of "seeing" the flow. For example, the above input flow can also be reassembled. Referring to the JDK help document, we can find that the construction method of buffered input character stream is as follows: BufferedReader(Reader in)
The parameter description can be used as the parameter of BufferedReader as long as it is a subclass of Reader, so it can be written as:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\text.txt") ) );
Although the content in the stream is the same, the perspective of br and ins is different. ins is read character by character, while br is read line by line.

4. What is the function of filtering flow (assembly of flow) in Java? Please give an example of a commonly used filter stream.

Abstract InputStream and OutputStream classes allow us to read and write strings and numbers. To achieve this, more functional subclasses are needed. For example: DateInputStream and DataOutputStream allow us to read and write all basic java types. The file stream class is similar to the abstract InputStream and OutputStream classes, which only support byte level read and write operations. In other words, only character and byte arrays can be read from the fin object. byte b=fin.read(), they don't provide a special value type, so DataInputStream can't get numbers from a file.
Solution: java divides the responsibilities of streams, and some streams (fileinputstreams) are responsible for reading byte data from files or other more special places. Other streams (DataInputStream, PrintWriter) are responsible for "assembling" bytes into more useful data types. These two streams must be combined into so-called "filtered streams" by passing one ready-made stream to the builder of another stream.

Example: reading a number from a file

  • Steps:
    1) Create a FileInputStream;
    2) Pass it to the constructor of a DataInputStream;

  • code:
    1)FileInputStream fin=new FileInputStream("a.txt");
    2)DataInputStream din=new DataInputStream(fin); double s=din.readDouble();

  • Demo program:

---------------------------------*   Read numbers from a file  *-------------------------------------
import java.io.*;
import java.lang.*;
public class B
{
 public static void main(String args[])
 {
 
  try
  {
   FileOutputStream fin1=new FileOutputStream("a.txt");
   DataOutputStream din1=new DataOutputStream(fin1);
   din1.writeDouble(102);

   FileInputStream fin2=new FileInputStream("a.txt");
   DataInputStream din2=new DataInputStream(fin2);
   Double d= new Double(din2.readDouble());

   System.out.println("read message is : "+d.toString());
   din2.close();
   fin2.close();
   din1.close();
   fin1.close();
  
  }
  catch(Exception e)
  {}
 }
}
  • Supplementary knowledge:

By default, streams are not buffered. That is, each time it is read, the operating system will be required to provide a byte. Through BufferedInputStream and
BufferedOutputStream is filtered and layered by the convection builder to realize buffering.

  1. Constructor:
   BufferedInputStream(InputStream in)
   BufferedInputStream(InputStream in, int size) //Size: the size of the buffer
  1. Code demonstration:
   BufferedInputStream bis=new BufferedInputStream(System.in);
   BufferedInputStream bis=new BufferedInputStream(System.in ,100);
  1. Examples of procedures:
//-----------*Buffer the a.txt file and input data*---------------
import  java.io.*;
import  java.util.*;
import java.lang.*;
public class BB
{
 public static void main(String args[])
 {
  try
  {
   DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream("a.txt")));
   byte[] c=new byte[10];
 
   while(dis.read(c)!=-1)
   {
    for(int i=0;i<10;i++)
    System.out.println("the message is "+String.valueOf(c[i]));}
 
  }catch(Exception e){}
 }
}                    

5. What is object serialization and deserialization? What support does Java provide for this?

  • definition:
    The process of converting an object into a sequence of bytes is called object serialization.
    The process of restoring a byte sequence to an object is called object deserialization.
    The serialization process is done on the server side; Deserialization is done on the client side.
  • Object serialization has two main purposes:
  • Save the byte sequence of the object permanently to the hard disk, usually in a file;
  • A sequence of bytes that transfers objects over a network.
  • In Java, we can create objects in many ways, and we can reuse them as long as they are not recycled. However, these objects we created exist in the heap memory of the JVM. These objects can exist only when the JVM is running. Once the JVM stops, these objects disappear. However, in real application scenarios, we need to persist these objects and re read them when necessary. Java serialization can help us realize this function. Object serialization is a built-in object persistence method in Java language. Through object serialization, the state information of the object can be saved without byte array, and this byte array can be converted into an object through deserialization when necessary. The serialization of the object can be easily converted between the active object and the byte array (stream) in the JVM.

6. What does the java File class represent? What does it do?
Java File classes represent File names and directory pathnames in an abstract way. This class is mainly used to create files and directories, find files and delete files. The File object represents the files and directories that actually exist on the disk.

public class DirList {
    public static void main(String args[]) {
        String dirname = "/java";
        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");
        }                                                                                                                                                                                                                                                                                                                                                                             
    }
}

7. What support does Java provide for reading and writing files?
Reading files in bytes is often used to read binary files, such as pictures, sounds, images and other files. Read files in character units. It is often used to read text, numbers and other types of files.

//------------------References---------------------------------
//
//1. Read file contents by byte
//2. Read file contents by characters
//3. Read file contents by line
//4. Random reading of file contents
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
 
public class ReadFromFile {
	/**
	 * Reading files in bytes is often used to read binary files, such as pictures, sounds, images and other files.
	 * 
	 * fileName
	 *            File name
	 */
	public static void readFileByBytes(String fileName) {
		File file = new File(fileName);
		InputStream in = null;
		try {
			System.out.println("Read the file contents in bytes, one byte at a time:");
			// Read one byte at a time
			in = new FileInputStream(file);
			int tempbyte;
			while ((tempbyte = in.read()) != -1) {
				System.out.write(tempbyte);
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		try {
			System.out.println("Read the file contents in bytes, and read multiple bytes at a time:");
			// Read multiple bytes at a time
			byte[] tempbytes = new byte[100];
			int byteread = 0;
			in = new FileInputStream(fileName);
			ReadFromFile.showAvailableBytes(in);
			// Read multiple bytes into the byte array. Byte read is the number of bytes read at one time
			while ((byteread = in.read(tempbytes)) != -1) {
				System.out.write(tempbytes, 0, byteread);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
				}
			}
		}
	}
 
	/**
	 * Read files in character units. It is often used to read text, numbers and other types of files
	 * 
	 * fileName
	 *            file name
	 */
	public static void readFileByChars(String fileName) {
		File file = new File(fileName);
		Reader reader = null;
		try {
			System.out.println("Read the file contents in characters, one byte at a time:");
			// Read one character at a time
			reader = new InputStreamReader(new FileInputStream(file));
			int tempchar;
			while ((tempchar = reader.read()) != -1) {
				// For windows, rn when these two characters are together, it means a line break.
				// However, if the two characters are displayed separately, the line will be changed twice.
				// Therefore, r is shielded, or n is shielded. Otherwise, there will be a lot of empty lines.
				if (((char) tempchar) != 'r') {
					System.out.print((char) tempchar);
				}
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			System.out.println("Read the file contents in character units, and read multiple bytes at a time:");
			// Read more than one character at a time
			char[] tempchars = new char[30];
			int charread = 0;
			reader = new InputStreamReader(new FileInputStream(fileName));
			// Read multiple characters into the character array. charread is the number of characters read at a time
			while ((charread = reader.read(tempchars)) != -1) {
				// Similarly, r is masked and not displayed
				if ((charread == tempchars.length)
						&& (tempchars[tempchars.length - 1] != 'r')) {
					System.out.print(tempchars);
				} else {
					for (int i = 0; i < charread; i++) {
						if (tempchars[i] == 'r') {
							continue;
						} else {
							System.out.print(tempchars[i]);
						}
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}
 
	/**
	 * Read files in behavioral units, which is often used to read line oriented format files
	 * 
	 * fileName
	 *            file name
	 */
	public static void readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			System.out.println("Read the contents of the file in behavioral units, one whole line at a time:");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// Read in one line at a time until the end of reading in a null file
			while ((tempString = reader.readLine()) != null) {
				// set number 
				System.out.println("line " + line + ": " + tempString);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}
 
	/**
	 * Random reading of file contents
	 * 
	 * fileName
	 *            file name
	 */
	public static void readFileByRandomAccess(String fileName) {
		RandomAccessFile randomFile = null;
		try {
			System.out.println("Read a section of file at random:");
			// Open a random access file stream as read-only
			randomFile = new RandomAccessFile(fileName, "r");
			// File length, bytes
			long fileLength = randomFile.length();
			// Start position of read file
			int beginIndex = (fileLength > 4) ? 4 : 0;
			// Move the start position of the read file to the beginIndex position.
			randomFile.seek(beginIndex);
			byte[] bytes = new byte[10];
			int byteread = 0;
			// If there are less than 10 bytes left in the file, read it once.
			// Assign the number of bytes read at one time to byteread
			while ((byteread = randomFile.read(bytes)) != -1) {
				System.out.write(bytes, 0, byteread);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (randomFile != null) {
				try {
					randomFile.close();
				} catch (IOException e1) {
				}
			}
		}
	}
 
	/**
	 * Displays the number of bytes left in the input stream
	 */
	private static void showAvailableBytes(InputStream in) {
		try {
			System.out.println("The number of bytes in the current byte input stream is:" + in.available());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
	public static void main(String[] args) {
		String fileName = "C:/temp/newTemp.txt";
		ReadFromFile.readFileByBytes(fileName);
		ReadFromFile.readFileByChars(fileName);
		ReadFromFile.readFileByLines(fileName);
		ReadFromFile.readFileByRandomAccess(fileName);
	}
}

Copying text files using character stream buffer can improve efficiency. Reader has a subclass BufferedReader, which inherits the parent class. Obviously, subclasses can override the methods of the parent class and add their own new methods. For example, reading one line at a time is a common operation The BufferedReader class provides this method. You can see that the readLine() method has the function of reading one text line at a time. Obviously, this subclass can enhance the function.

private static void copyFile(File srcFile, File destFile)throws IOException {
        // Create character input stream
        FileReader fr = new FileReader(srcFile);
        // Create character output stream
        FileWriter fw = new FileWriter(destFile);

        // Buffer stream of character input stream
        BufferedReader br = new BufferedReader(fr);
        // Buffer stream of character output stream
        BufferedWriter bw = new BufferedWriter(fw);

        String line = null;
        // Read one line at a time
        while ((line = br.readLine()) != null) {
            // Write one line at a time
            bw.write(line);
            // Refresh buffer
            bw.flush();
            // Line feed, because the readLine method has no line feed by default Need to wrap lines manually
            bw.newLine();
        }
        // Close flow
        br.close();
        bw.close();
    }

Tags: Java

Posted by snipe7kills on Mon, 02 May 2022 11:10:36 +0300