Java input / output stream

Keywords: Java

Input / output stream

Introduction:
Input / output:

Input/Output refers to the input or output of data to a device or environment. Any language has the function of input and output. In Java programs, the input and output are completed through streams. It is connected to physical devices through Java input and output system. Although the actual physical devices connected by input and output streams are different, But it can work in the same way. For example, input and output to hard disk and input and output to network host. Therefore, different equipment or environment will have various input and output problems and solutions

Flow:

Stream refers to the data sequence moving between the input and output of the computer. The data in the stream sequence can be either unprocessed original binary data or specific data conforming to a certain format after certain coding processing. Traditionally, the part related to the code is called internal, and the part unrelated to the code is called external

In terms of data transmission mode, data stream can be divided into input stream and output stream; From the content of stream, stream can be divided into byte stream and character stream

classification
By processing unit:
  • Character stream: the operation data unit is a character. Reader Writer is an abstract operation base class
  • Byte stream: the operation data unit is a character InputStream and OutputStream is an abstract operation base class
According to the function of flow:
  • Node flow: the program is directly connected with the data source and the actual input / output node;

  • Processing flow: wrap the node flow, expand the original function, and perform IO operations by the processing flow.

  • Classification and function of processing flow:

    • Function: the processing flow can hide the difference of node flow on the underlying device, without caring about the source of data source. The program only needs to perform IO operations through the processing flow. The processing flow takes the node flow as the construction parameter. In general, it is recommended to use processing flow to complete IO operations

    • Classification:

      • Buffer stream: provide a buffer, which can improve the execution efficiency of input / output and reduce frequent operations at the same node.

        • BufferedInputStream/BufferedOutputStream,BufferedReader/BufferWriter
          
      • Convert stream: stream bytes into characters. Byte stream is widely used, but character stream is more convenient. For example, if the data source of a byte stream is plain text, it is better to convert it into a character stream for processing

        • InputStreamReader/OutputStreamWriter
          
      • Printout stream: prints out the specified content, and determines where to output according to the node stream in the construction parameters.

        • PrintStream : Print out byte data. PrintWriter :  Print out text data.
          
There are three types of data sources in I/O flows:
Disk file:

FileInputStream,FileOutputSteam,FileReader,FileWriter

Memory:

Bytearrayinputstream bytearrayunputstream (ps: byte arrays are generated in memory)

Network:

SocketInputStream, SocketInputStream (ps: data transmission during network communication)

graphic

The File class operates on the properties of a File or directory

attribute

Listed are common. fs refers to the current system.

    • attributeeffectunderstand
      static charThe pathSeparatorChar system relies on the path separator character.
      static StringThe default name separator character that the separator system relies on, expressed as a convenient string.File. Separator: on UNIX systems, the value of this field is' / '; Microsoft Windows is' \ \ '
      static charseparatorChar is the default name separator character that the system depends on.
      static StringThe pathSeparator system relies on the characters of the path separator, expressed as a convenient string.Path separator, semicolon under win, colon on Linux
Construction:
  • File(String pathname); Create from pathname
  • File(URL url); Create from a URL
  • File(File parent, String child); Create under the given file object
  • File(String parent, String child); Create according to the specified path
common method
    • Return typemethod
      booleancanExecute() tests whether the application is an abstraction represented by the path name of the executable file.
      booleancanRead() checks whether the application can read the abstract pathname of the file.
      booleancanWrite() checks whether the application can modify the abstract pathname of the file.
      intcompareTo(File pathname) compares the dictionaries of two abstract pathnames.
      booleancreateNewFile() automatically creates a new empty file named abstract pathname if and only if the file does not exist.
      static FilecreateTempFile(String prefix, String suffix) creates an empty file in the default temporary file directory and generates its name with the given prefix and suffix.
      static FilecreateTempFile(String prefix, String suffix, File directory) creates a new empty file in the specified directory and generates its name using the given prefix and suffix string.
      booleandelete() deletes the abstraction represented by the pathname of a file or directory.
      voidWhen the abstract pathname of the file or directory requested by deleteOnExit() is deleted, the virtual machine terminates.
      booleanequals(Object obj) tests that the abstract pathname is equal to the given object.
      booleanexists() checks whether such abstract pathnames exist for files or directories.
      FilegetAbsoluteFile() returns the absolute form of this abstract pathname.
      StringgetAbsolutePath() returns the string of the absolute pathname of this abstract pathname.
      FilegetCanonicalFile() returns the canonical form of this abstract pathname.
      StringgetCanonicalPath() returns the specification file for this abstract pathname.
      longgetFreeSpace() returns the path in the partition through this abstract pathname named Number of bytes not allocated.
      StringgetName() returns the abstraction represented by the pathname of the file or directory of the name.
      StringgetParent() returns the string of the parent pathname of this abstract pathname, or null if the pathname is not called the parent directory.
      FilegetParentFile() returns the parent abstract pathname of this abstract pathname, pathname or null if this is not called the parent directory.
      StringgetPath() converts the abstract path name to a string of pathnames.
      longgetTotalSpace() returns the partition with this abstract pathname named size.
      longgetUsableSpace() uses this abstract pathname named Returns the number of bytes of available virtual machines on the partition.
      inthashCode() calculates the abstract pathname of the hash code.
      booleanisAbsolute() tests whether the abstract pathname is absolute.
      booleanisDirectory() tests whether the file is represented as a directory by this abstract pathname.
      booleanisFile() tests whether the file represents a normal file by this abstract pathname.
      booleanisHidden() tests whether the file is named as a hidden file through this abstract pathname.
      longlastModified() returns the abstract pathname of the file, indicating the last modified time.
      longlength() returns the length represented by the abstract pathname of the file.
      String[]The file and directory of the abstract pathname of the string returned by list() in this directory are named array.
      String[]List (filenamefilter) the abstract pathname of the returned string in the directory, which meets the specified filter and represents the file and directory naming array.
      File[]listFiles() returns an array of files in the directory representing the abstract pathname.
      File[]Listfiles (filefilter) returns the directory of the file and directory represented by the abstract pathname. This abstract pathname satisfies the specified filter representation array.
      File[]Listfiles (filenamefilter) returns the directory of the file and directory represented by the abstract pathname. This abstract pathname satisfies the specified filter representation array.
      static File[]listRoots() lists the available file system roots.
      booleanmkdir() creates an abstract path name under this directory.
      booleanmkdirs() creates an abstract pathname naming under this directory, including any necessary but non-existent parent directory.
      booleanrenameTo(File dest) renames the abstract pathname of the file.
      booleansetExecutable(boolean executable) is a convenient method for the owner's abstract pathname to execute permissions.
      booleansetExecutable(boolean executable, boolean ownerOnly) sets the execution permission of this abstract pathname of the owner or everyone.
      booleansetLastModified(long time) sets the last modification time of the abstract pathname naming of the file or directory.
      booleansetReadable(boolean readable) is a convenient method to provide the owner of this abstract pathname set with read permission.
      booleansetReadable(boolean readable, boolean ownerOnly) sets the read permission of the abstract pathname of the owner or everyone.
      booleansetReadOnly() tags files or directories named by this abstract pathname, and only read operations are allowed.
      booleansetWritable(boolean writable) is a convenient method to set the owner's permission to write this abstract pathname.
      booleansetWritable(boolean writable, boolean ownerOnly) is the permission of the owner of the set or everyone to write this abstract pathname.
      PathtoPath() returns a java.nio.file.Path Objects are represented by abstract paths.
      StringtoString() returns the file with this abstract pathname.
      URItoURI() builds a file: URI that represents this abstract pathname.
      URLtoURL() is out of date. This method does not automatically escape characters that are illegal in the web address. It is suggested that the new code be converted into an abstract pathname URL. First, convert it into a URI through toURI Method, and then convert it into a URL URI URI.toURL method.
Common examples
package com.bigdata.practice1007;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

public class FileTest {

	public static void main(String[] args) throws IOException {
		// Create delete get descriptor of file
		String path = "D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"io";
		createFolder(path);
		createFile(path,fileName);
		listFile("C:/");
		listDisk();
		fileInfo(path, fileName);
		deleteFile(path + File.separator + fileName);
	}

	/**
	 * display file information
	 * length():Method to get the file size
	 * lastModified():Method is used to get the return string of the last operation time of the file
	 */
	public static void fileInfo(String path, String fileName){
		File file = new File(path, fileName);
		System.out.println("File size:" + file.length() + "byte");
		System.out.println("Last modified date:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss").format(file.lastModified()));
	}

	/**
	 * Delete file
	 * file.delete():Delete file
	 * file.exists():Determine whether the file exists
	 * file.isFile():Determine whether the file points to a file
	 * file.canExecute():Determine whether the file can be deleted
	 */
	public static void deleteFile(String fileFullName){
		File file = new File(fileFullName);
		if (!file.exists()){
			System.out.println("File does not exist!");
			return;
		}
		if (!file.isFile()){
			System.out.println(fileFullName + "Not a file, stop deleting!");
			return;
		}
		if (file.canExecute()) {
			file.delete();
		}else {
			System.out.println("No permission to delete!");
		}
	}

	/**
	 * Create directory
	 * file.mkdirs():Used to create multi-level directories
	 * file.mkdir():Used to create stand-alone directories
	 */
	public static void createFolder(String path){
		File file = new File(path);
		if (!file.exists()){
			file.mkdirs();
		}
	}

	/**
	 * create a file
	 * file.createNewFile():For creating files only
	 */
	public static void createFile(String path, String fileName) throws IOException{
		File file = new File(path, fileName);
		if (!file.exists()){
			file.createNewFile();
		}
	}

	/**
	 * Displays subdirectories and files in the specified directory
	 * file.listFiles():It is used to get subdirectories and files in the specified directory. It is not recursive
	 * files[i].isDirectory():Determine whether to point to the directory
	 * files[i].getAbsolutePath():Retrieve absolute path
	 * files[i].getName():Get file name
	 */
	public static void listFile(String diskName){
		File file = new File(diskName);
		File[] files = file.listFiles();
		if (files != null && files.length > 0){
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()){
					System.out.println("Directory name:" + files[i].getAbsolutePath());
				}
				if (files[i].isFile()){
					System.out.println("File name:" + files[i].getName());
				}
			}
		}
	}

	/**
	 * Displays the system disk and disk space
	 * File.listRoots():Get all drive letters by static method
	 * disks[i].getTotalSpace():Total disk size
	 * disks[i].getFreeSpace():Disk free space
	 */
	public static void listDisk(){
		File[] disks = File.listRoots();
		if (disks != null && disks.length > 0){
			for (int i = 0; i < disks.length; i++) {
				System.out.println("Disk:" + disks[i]);
				System.out.println("Disk size:" + disks[i].getTotalSpace() / 1000 / 1000 /1000 + "G");
				System.out.println("Disk free space:" + disks[i].getFreeSpace() / 1000 / 1000 /1000 + "G");
			}
		}
	}
}

Byte stream reads and writes any file

Byte streams BufferedOutputStream and FileOutputStream read and write files
Byte streams BufferedInputStream and FileInputStream read files
package com.bigdata.practice1007;

import java.io.*;

public class IOTest {
	public static void main(String[] args) {
		try {
			byteOutput();
			byteInput();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * OutputStream The file output stream, a subclass of byte output stream, is used to output data in memory to a file
	 * BufferedOutputStream These two can increase the efficiency of the above byte input-output operation
	 * 1.Import related classes
	 * 2.Create a file output stream object create a cached output stream object and wrap the file output stream object
	 * 3.Convert the string object to be input into a byte array [str.getBytes()]
	 * 4.Use the write method to write the data in the byte array to the file
	 * 5.Close both streams
	 */
	public static void byteOutput() throws  Exception{
		File file = new File("D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"io"+File.separator+"bbb.txt");
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			String str = "ABC You are?";
			byte[] bytes = str.getBytes();
			bos.write(bytes, 0, bytes.length);
			System.out.println("Write complete!");
		} catch(IOException e){
			System.out.println("Error creating file!");
		}
		finally {
			bos.close();
			fos.close();
		}
	}

	/**
	 * InputStream The subclass of byte input stream FileInputStream is used to read the data in the file into the java program
	 * BufferedInputStream Speed up
	 * 1.Guide Package
	 * 2.Create file byte input stream and corresponding cache byte input stream
	 * 3.Given read byte array [fis.available()] and string variable [for output]
	 * 4.while Loop to read the data of byte array
	 * 5,Print: convert byte array to String
	 * 6.Close both streams
	 */
	public static void byteInput() throws Exception{
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try{
			fis = new FileInputStream("D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"io"+File.separator+"bbb.txt");
			bis = new BufferedInputStream(fis);
			System.out.println("Bytes that can be read:" + fis.available());
			System.out.println("File content:");
			String str = "";
			byte[] bytes = new byte[fis.available()];
			while(bis.read(bytes) != -1){
				str = new String(bytes);
			}
			System.out.println(str);
		}catch(Exception e){
			System.out.println("Error reading file!");
		}finally{
			bis.close();
			fis.close();
		}
	}
}

Character stream reading and writing text file

package com.bigdata.practice1007;

import java.io.*;

public class IOTest1 {
    /**
     * Read and write text files using character streams
     */
    public static void main(String[] args) {
        try {
            charWrite();
            charReader();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Writing a character stream to a text file
     * BufferedWriter And FileWriter are subclasses of Writer
     * bw.write("AAA");:Write character text to cache
     * bw.newLine();:Line feed
     * bw.flush();:Flushes the cache and writes data to a text file
     */
    public static void charWrite() throws IOException{
        File file = new File("D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"io"+File.separator+"ccc.txt");
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write("Writing a character stream to a text file");
            bw.newLine();
            bw.write("AAA");
            bw.flush();
            System.out.println("Write complete!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            bw.close();
            fw.close();
        }
    }

    /**
     * Character stream read text file
     * FileReader And BufferedReader are subclasses of Reader
     *
     */
    public static void charReader() throws Exception{
        FileReader fr = null;
        BufferedReader br = null;
        try{
            fr = new FileReader("D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"io"+File.separator+"ccc.txt");
            br = new BufferedReader(fr);
            String str = "";
            while((str = br.readLine()) != null){
                System.out.println(str);
            }
        }catch (Exception e) {
            System.out.println("Error reading file!");
        } finally {
            br.close();
            fr.close();
        }
    }
}

Character stream read and write throttling

Introduction:

InputStreamReader OutputStreamWriter: byte input / output stream. You can specify the encoding method, convert byte stream to character stream, and perform read / write operations

situation:
  • The default character encoding format is not used, and the encoding format needs to be specified;
  • The third party provides a byte based stream and wants to wrap it as a character based stream
Example:
  • When using FileOutputStream and FileWrite to output data, ASAN encoding format is used by default
  • If you want to specify the encoding method when outputting, you need to use OutputStreamWriter
package com.bigdata.practice1007;

import java.io.*;

public class IOTest2 {
    /**
     * Read and write using character stream
     */
    public static void main(String[] args) {
       outputStreamWriter();
       inputStreamReader();
    }
    /**
     * Read and write in character stream
     * InputStreamReader OutputStreamWriter : Byte input / output stream. You can specify the encoding method, convert the byte stream into character stream, and read and write
     * Usage: the default character encoding format is not used, and the encoding format needs to be specified; The third party provides a byte based stream and wants to wrap it as a character based stream
     *
     * When using FileOutputStream and FileWrite to output data, ASAN is used by default. If you want to specify the encoding method during output, you need to use OutputStreamWriter
     */

    public static void outputStreamWriter(){
        try{
            File file = new File("D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"io"+File.separator+"ddd.txt");
            FileOutputStream fos = new FileOutputStream(file, true);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
            BufferedWriter bw = new BufferedWriter(osw);
            if (!file.exists()){
                file.createNewFile();
            }
            bw.write("I am not ANSI Code format!");
            bw.newLine();
            bw.write("But UTF-8 Coded!");
            bw.flush();
            System.out.println("Write complete!");
            bw.close();
            osw.close();
            fos.close();
        } catch (FileNotFoundException e) {
            System.out.println("file cannot be found");
        }catch (IOException e1) {
            System.out.println("Write failed!");
        }
    }

    public static void inputStreamReader(){
        try{
            File file = new File("D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"io"+File.separator+"ddd.txt");
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String app;
            while((app = br.readLine()) != null){
                System.out.println(app);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
        }  catch (IOException e) {
            System.out.println("Read failed!");
        }
    }
}

Read / write binary file

Copy file
  • [generally, files that cannot be opened with Notepad can be operated]
package com.bigdata.practice1007;

import java.io.*;

public class CopyFile {
    /**
     * Reading and writing of binary files
     * Use byte stream to read and write binary files: common classes are DataInputStream and DataOutputStream
     */
    private  String sourcePath;
    private  String distPath;

    public CopyFile(){

    }

    public CopyFile(String sourcePath, String distPath){
        this.sourcePath = sourcePath;
        this.distPath = distPath;
    }

    /**
     * Do you want to delete the source file
     * @param sourcePath
     * @param distPath
     * @param flag
     */
    private static void deletSourceFile(String sourcePath, String distPath, boolean flag) {
        File file1 = new File(sourcePath);
        File file2 = new File(distPath);
        if (flag == true && file2.exists() && file2.length() == file1.length()){
            file1.delete();
        }
    }

    /**
     * Copy binary file [file that Notepad cannot open]
     * @param sourcePath  Original file path
     * @param distPath  Copy file destination path
     * 1.Establish input stream
     * 2.Create an output stream [remember to handle exceptions: throw call processing; internal processing]
     * 3.Read / write operation
     * 4.Close flow
     */
    private static boolean copyFile(String sourcePath, String distPath) {

        if (sourcePath != null && distPath != null) {
            File file1 = new File(sourcePath);
            File file2 = new File(distPath);
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(file1);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);

                fos = new FileOutputStream(file2);
                BufferedOutputStream bos  = new BufferedOutputStream(fos);
                DataOutputStream dos = new DataOutputStream(bos);
                int num;
                while ((num = dis.read()) != -1) {
                    dos.write(num);
                }
                dos.flush();
                dos.close();
                bos.close();
                fos.close();
                dis.close();
                bis.close();
                fis.close();
            }
            catch(IOException e){
                System.out.println("Copy error!");
                e.printStackTrace();
            }
            System.out.println("Copy succeeded!");
            return true;
        } else {
            System.out.println("The file name passed in is not appropriate!");
            return false;
        }
    }

    /**
     * test
     */
//    public static void main(String[] args) {
//        String sourcePath = "D:"+File.separator+"kaifamiao"+File.separator + "Alibaba Java development manual v1.2.0.pdf";
//        String distPath = "D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator + "Alibaba java development manual v1.2.0.pdf";
//        boolean flag = copyFile(sourcePath, distPath);
//        deletSourceFile(sourcePath, distPath, flag);
//    }
}

Read the web source code to the local file

package com.bigdata.practice1007;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetDataTest {
	/**
	 * Take the source code from the network and save it to a file
	 * 1.website
	 * 2.Establish a network connection
	 * 3.Establish input / output stream
	 * 4.Read data
	 * 5.Output to console and save to file
	 * 6.Close input / output stream
	 */
	public static void main(String[] args) {
		// 1. Website
		String str = "https://mirrors.tuna.tsinghua.edu.cn/";
		
		try {
			URL url = new URL(str);
			
			// 2. Establish network connection
			HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
			
			// 3. Establish input / output flow
			InputStream is = httpConn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			
			File file = new File("D:"+File.separator+"kaifamiao"+File.separator+"java se"+File.separator+"mirrors.html");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file, true);
			BufferedWriter bw = new BufferedWriter(fw);
			
			// 4. Read data
			String data;	// Save and read each row of data to the cache
			StringBuilder sb = new StringBuilder(); // Append all data stored and output to the console
			while ((data = br.readLine()) != null) {
				sb.append(data + "/n");
				bw.write(data);
				bw.newLine();
			}
			
			// 5. Output
			System.out.println(sb);
			bw.flush(); // Empty the cache and write the data to the file
			
			// 6. Close
			br.close();
			is.close();
			bw.close();
			fw.close();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Posted by servo on Sat, 23 Oct 2021 19:28:29 -0700