IO flow based on JAVA

IO flow based on JAVA

I concept
IO stream: a mechanism for transmitting data

1: Input
O: Output

Stored data: memory persistent storage
Persistent storage: long term storage

IO stream is divided into input stream and output stream
IO stream is functionally divided into character stream and byte stream
The character stream can only manipulate characters (txt,. java,. html)
Byte stream: all files can be manipulated

Input streamOutput stream
Character streamReaderWriter
Byte streamInputStreamOutputStream

The above four are abstract classes and cannot be used directly

Input or output is relative to memory
If the content is read into memory, it is input into memory. Input stream
If you write content from memory to the outside, it is output.

Character output stream: FileWriter writes characters to a file
If you want to append data, provide true after the constructor

II Character output stream
1. Character output stream

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo {
	public static void main(String[] args) throws IOException {
		// Character output stream
		// If there is a path, create the file directly
		// If the file already exists, a new file will be created to overwrite the original file
		FileWriter fw = new FileWriter("F:\\a.txt",true);//Add to a.txt without overwriting

		// Write data to buffer
		fw.write("I wish the breeze is not dry, the sun is just right, and the time is not old~");
		// Scour buffer zone
//		fw.flush();
		// Close and release resources
		// The buffer is automatically flushed when closed
		fw.close();
		// Empty object
		fw = null;
	}
}

2. Handling exceptions

Exception handling:
1. First declare the object outside try... catch and set it to null to ensure that the scope of the object is in try... catch... finally
2. Create an object and judge whether it is null in finally. Because once the object is null, a null pointer exception will occur.
3. In the finally judgment method, close the flow. Closing the flow also needs to catch exceptions, because closing the flow is not necessarily successful.
4. Add finally to the try catch that catches the closed flow exception, and set the object to null whether the closed flow is successful or not.
5. If you write data, you need to flush the buffer to prevent data loss.

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExceptioonTest {
	public static void main(String[] args) {
		
		// create object
		FileWriter fw = null;
		try {
			fw = new FileWriter("F:\\b.txt");
			fw.write("Hello, hello world");
			// scour
			fw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if (fw != null){
				try {
					fw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					fw = null;
				}
			}
		}
	}
}

3.JDK1. Characteristics of 7
Try with resource
Try (subclass / sub interface of autoclosable){
Objects can be guaranteed to close automatically
}
Note: the contents in try parentheses cannot be passed on

import java.io.FileWriter;

public class TryWithResourceDemo {
	public static void main(String[] args) {
		
		// JDK1.7 characteristics
		// try ...  with ...  Reset can ensure automatic shutdown
		// Use the format try (subclass or sub interface of autoclosable)
		// It can ensure that the objects inside are automatically closed
		try (FileWriter fw = new FileWriter("F:\\b.txt")){    //Notice the parentheses
			fw.write("Goodbye, Jay Chou");
		}catch(Exception e){
			e.printStackTrace();
		}

	}
}

III Character input stream: FileReader
FileReader reads one character at a time by default, which is inefficient. You can form a buffer through the character array to improve efficiency.
1. Read the contents of the file into the character input stream in memory

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
	public static void main(String[] args) throws IOException {
		// Read the contents of the file into the character input stream in memory
		// create object
		FileReader fr = new FileReader("F:\\c.txt");
		// Read character
		// Read one character at a time
		// If there is no character at the end of the reading, return - 1
		// Because it is read one by one from the file, this writing method is relatively inefficient
		int ch;
		while ((ch = fr.read()) != -1){
			// Read once print once
			System.out.println((char)ch);
		}
		// Close flow
		fr.close();
	}
}

2. Use the character array as the buffer to read the number of characters

import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo02 {
	public static void main(String[] args) throws IOException {
		// Read data through the character array as a buffer
		FileReader fr = new FileReader("F:\\c.txt");
		// Define a character array
		char[] chs = new char[3];
		
		// Read once to get the content of the corresponding character array length
		// If no data is read, - 1 is returned
		// Read character length
		int len;
		while((len = fr.read(chs)) != -1){
			System.out.println(new String(chs,0,len));
		}
		
		
		fr.close();
	}
}

3. Copy files

import java.io.FileReader;
import java.io.FileWriter;

public class CopyTxt {
	public static void main(String[] args) {
		// Idea of copying files: read the contents in the corresponding files first
		// Read one line and write one line
		// Use character array when reading
		
		long startTime = System.currentTimeMillis();
		FileReader fr = null;
		FileWriter fw = null;
		try{
			fr = new FileReader("F:\\a.txt");
			fw = new FileWriter("F:\\b.txt");
			
			// Read before write
			// If the character array needs to be used for reading, create the array first
			char[] chs = new char[1024 * 8];
			// Define a variable to receive the actual read length
			int len;
			while ((len = fr.read(chs)) != -1){
				// Indicates that the content is read, and the length is len
				// Write to file
//				fw.write(new String(chs,0,len));
				fw.write(chs, 0, len);
			}
			fw.flush();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			// Both fr and fw can be null
			if (fr != null){
				try{
					fr.close();
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					fr = null;
				}
			}
			
			if (fw != null){
				try{
					fw.close();
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					fw = null;
				}
			}
		}
		// Total time spent copying text
		System.out.println(System.currentTimeMillis() - startTime);
	}
}

IV BufferedReader and BufferedReader

BufferedReader: a buffer is provided by default, which is more efficient than FileReader. The bottom layer still uses FileReader to read
BufferedReader: provides a unique method, readLine, which can read one line of string at a time
Note: readLine does not read line breaks \ r\n

Design pattern: a common means to solve the same kind of problems.
Decoration design pattern: use similar objects to build this kind of objects, so as to enhance or repair the functions of the built objects.
BufferedReader and BufferedWriter are the so-called decoration design patterns

1.BufferedReader

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		// create object
		// Incoming FileReader object
		// The bottom layer uses FileReader
		BufferedReader br = new BufferedReader(new FileReader("F:\\667.txt"));
		
		// You can read one line at a time
		String str;
		while((str = br.readLine()) != null){
			System.out.println(str);
		}
		
		// Close flow
		br.close();
		
	}
}

2.BufferedReader
BufferedWriter: write data. A unique method (newLine) is provided to wrap lines.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterDemo {
	public static void main(String[] args) throws IOException {
		// create object
		BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\a689.txt"));
		bw.write("Love this cup of wine, who will drink drunk");
		// Line feed
		bw.newLine();
		bw.write("What love, what forever!!");
		
//		bw.flush();
		bw.close();
	}
}

3. Count the number of java code lines

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class PracticeDemo {
	static int javaCount = 0;
	public static void main(String[] args) throws IOException {
		// Number of lines of code in unified workspace
		// The code is written in java file
		// Find it first java file
		// Then read a row through BufferedReader
		// Then count the number of rows
		
		// File class to manipulate files and directories
		File file = new File("F:\\workspace");
		count(file);
		System.out.println("A total of" + javaCount + "Line code");
	}
	
	// Define a method to find java file
	public static void count(File file) throws IOException{
		if (file.isDirectory()){
			// If it is a directory, list all contents of the directory
			File[] files = file.listFiles();
			for (File f : files) {
				count(f);
			}
		}else if(file.getName().endsWith(".java")){
			// Find it Java file copytxt java
			BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()));
			String str;
			while ((str = br.readLine()) != null){
				javaCount++;
			}
			
			br.close();
		}
	}
}

V FileInputStream and OutputStreamWriter
1.FileInputStream

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamDemo {
	public static void main(String[] args) throws IOException {
		// The byte input stream is input into memory in the form of bytes
		FileInputStream fis = new FileInputStream("F:\\c.txt");
		
		// Define byte array for buffer
		byte[] bys = new byte[10];
		int len;
		while ((len = fis.read(bys)) != -1){
			System.out.println(new String(bys,0,len));
		}
		
		fis.close();
		
		
	}
}

2.OutputStreamWriter

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class OutPutStreamDemo {
	public static void main(String[] args) throws IOException {
		// The conversion output stream can convert a byte stream into a character stream
		// Byte streams can be used by writing characters
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("F:\\d.txt"));
		
		// Write data
		osw.write("4555645dfgdf");
		// Closed flow
		osw.close();
			}
}

3. Copy files using byte stream

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyJPG {
	public static void main(String[] args) throws IOException {
		// Create byte input and output streams
		FileInputStream fis = new FileInputStream("F:\\a.jpg");
		FileOutputStream fos = new FileOutputStream("F:\\b.jpg");
		
		// Read picture
		// Defines a byte array for the buffer
		byte[] bys = new byte[10];
		// Actual length read
		int len;
		
		while((len = fis.read(bys)) != -1){
			// When the code is executed here, it indicates that the reading is successful
			// Write data
			fos.write(bys, 0, len);
		}
		
		// Closed flow
		fos.close();
		fis.close();
	}
}

Vi System flow

System.inStandard input stream
System.outStream output standard
System.errStandard error flow

Standard output stream and standard error stream may have high concurrency problems. There may be different positions, and there may be no line break

Why didn't you turn off Scanner???
The Scanner uses system In system input stream, which is shared. There is only one system input stream in the program. When the Scanner is closed, the parameter system input flow in the Scanner will also be closed. It will cause the whole program to no longer use the system input stream.
If you see the system flow in the future, do not close it.
System streams are byte streams.

Tags: Java

Posted by axm on Mon, 18 Apr 2022 23:08:22 +0930