IO flow in Java

Posted by pendelton on Sun, 14 Jun 2020 09:59:29 +0200

IO stream, that is, the technology used to manipulate the content of a File. So before we talk about IO streams, we need to know about the File class.

1, File file class

1. File class introduction

File is used by Java to represent files / folders (directories). Files / folders on the hard disk can be operated in the program through the file class.

The File class is only used to represent the File / folder information (size, name), etc., but not to read and write files.

be careful:
new File(): the created file / folder is only in memory, not in the hard disk.
file.createNewFile(): creates a file on the hard disk based on the path of the file.
file.mkdir(): create a folder on the hard disk according to the path of the file.
file.exsts(): determine whether the specified file / folder exists in the path corresponding to the file.

2. Create files and actions on files

(1) Create a file on the specified path (in 3 ways):

public class Test {
	public static void main(String[] args) throws IOException {
		//1. Default path, that is, under the current project
		File file1 = new File("test01.txt");
		file1.createNewFile();
		
		//2. File path in package
		File file2 = new File("src/test02/test.txt");
		file2.createNewFile();
		
		//3. Absolute path
		File file3 = new File("D:/test/test.txt");
		file3.createNewFile();
		//File file3 = new File("D:\\test\\test.txt");
	}
}

PS:
If you use 2 or 3 to create a file object, an error will be reported when the path is written incorrectly.
(2) Operations on file objects

public class Test {
	public static void main(String[] args) throws IOException {
		//Default path, that is, under the current project
		File file = new File("test01.txt");
		
		boolean ok = file.createNewFile();
		System.out.println(ok);
		//1. Get file name
		String fileName = file.getName();
		//2. Get the absolute path to the file
		String filePath = file.getAbsolutePath();
		//3. Get the relative path of the file
		String path = file.getPath();
		//4. Get the parent directory of the file (under which directory)
		String parentPath = file.getParent();
		//5. Get whether the file is hidden
		boolean flag = file.isHidden();
		//6. Gets the number of bytes in the file
		long len = file.length();
		//7. Get the last modification time of the file
		long tempTime = file.lastModified();
		//8. Delete file
		boolean flag2 = file.delete();
		//9. See if the file exists
		boolean flag1 = file.exists();
		
		System.out.println("===================");
		
		//Fixed operation	
		if(!file.exists()) {//file does not exist
			System.out.println("The file name was not found in the specified directory“ test"Text file for, creating");
			try {
				file.createNewFile();
			}catch(IOException e) {
				e.printStackTrace();
			}
			System.out.println("File created successfully");
		}else {//File exists
			System.out.println("File name found“ test"Text file for");
			//You can continue working on files
		}
	}
}

3. Create folders and actions on folders

(1) Create folder
Basically similar to creating files.

public class Test {
	public static void main(String[] args) {
		//1. Create a single folder
		File dir1 = new File("dir");
		boolean flag1 = dir1.mkdir();
		//2. Create multiple folders
		File dir2 = new File("dir1/dir2/dir3/dir4");
		boolean flag2 = dir2.mkdirs();
	}
}

(2) Actions on folders

public class Test {
	public static void main(String[] args) throws IOException {
		File dir = new File("dir1/dir2/dir3/dir4");
		boolean flag = dir.mkdirs();
		//Delete the last folder of the file path
		boolean del =dir.delete();
	}
}

Create files under folders

public class Test {
	public static void main(String[] args) throws IOException {
		File dir = new File("dir");
		dir.mkdir();
		File file = new File(dir,"demo.txt");
		file.createNewFile();
	}
}

(3) Traverse the contents of a folder

public class Test {
	public static void main(String[] args) throws IOException {
		File dir = new File("E:/");
		//Get all the files and folders under disk E, and return the file array
		File[] fs = dir.listFiles();
		//ergodic
		for(File f:fs) {
			if(f.isFile()) {//Determine whether it is a document
				System.out.println(f.getName()+"It's a file");
			}
			if(f.isDirectory()) {//Determine whether it is a folder
				System.out.println(f.getName()+"It's a folder");
			}
		}
	}
}

2, IO flow (water pipe)

1. IO flow overview

(1) Definition:

IO stream is used to operate the file content technology, input and output are for the program.
I(in) input: input data into the program, generally reading content from the file into the program.
O(out) output: the program transfers data out, generally writing data to a file.

(2) Purpose:

Read and write files
Random code problem
Use of the underlying technology of the framework
Upload and download of files

(3) Classification:

By data type: byte stream, character stream.
Byte stream: binary 0101 (minimum unit), in bytes. It's universal. Any file can be operated.
Character stream: easy to operate Chinese characters (use Notepad to open without garbled code, you can use character stream)

According to the flow direction of data: input flow, output flow.

<1> Input stream
Byte Stream: Stream (read one byte at a time)
InputStream: abstract class
FileInputStream: file input stream (a subclass of InputStream)
BufferedInputStream: byte buffered input stream
--------------------------------------------------------------------
Character stream: Reader (one character at a time)
InputStreamReader
BufferedReader: character buffered input stream (read one line at a time)

<2> Output stream
Byte Stream: Stream
OutputStream: an abstract class
FileOutputStream: file output stream (a subclass of OutputStream)
BufferedOutputStream: byte buffered output stream
---------------------------------------------------------------------
Character stream: Writer (write one character at a time)
OutputStreamWriter
PrintWriter
BufferedWriter: character buffered output stream (write one line at a time)

be careful:
1. Byte buffer stream is more efficient than byte stream.
2. The byte buffer stream cannot directly operate on the file, so it must be wrapped and accessed through the byte stream.

2. Byte input stream and byte output stream

InputStream and OutputStream

OutputStream (program - > external)

(1) Basic framework

package test02;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Test {
	public static void main(String[] args){
		File file = new File("test.txt");
		OutputStream out = null;
		try {
			//OutputStream is an abstract class,
			//So you need to create an object through its subclass FileOutputStream
			out = new FileOutputStream(file);//Equivalent to opening the water pipe
			//To write to a file in bytes
			out.write('b');//b
			out.write(98);//b
			System.out.println("Write succeeded!");//As a reminder
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//If the output stream is not empty
			if(out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

be careful:
1. IOException is the parent of all exceptions in the IO stream.
2. If the file in FileOutputStream does not exist, the file will be automatically created under the corresponding path.
3. OutputStream is written to a file in bytes, so
'B' - > b; 48 - > 0; 98 - > b (ASCII)
4. After operating the file, be sure to close the stream, otherwise system resources will be consumed. Before closing a flow, you can first determine whether it is empty. If it is empty, it is unnecessary.

(2) Add or overwrite?

OutputStream out = new FileOutputStream(file,true);

If the position of the second parameter is true, it will be appended; if it is false, it will be overwritten. If the second parameter is not written, the default value is false.
(3) How to write String type?

String str = "1234567";
byte[] bs = str.getBytes();//Using getBytes() to get byte array
out.write(bs);//Parameter is of type byte array
out.write("\n".getBytes());//Output a space

Summary:
(1) If you want to use byte output stream to write "1234", "King" or enter to the file, you can use str.getBytes() parse them into byte arrays and write them to a file.
(2) If you write 97, 98 and other numbers directly, you will write the corresponding characters according to the ASCII code comparison table.
(3) Add to write to the file in the form of characters, i.e. 'b'. Then what appears in the file is also b.

InputStream (external - > program)

(1) Basic framework

test.txt Contents of the document:

package test02;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test {
	public static void main(String[] args){
		File file = new File("test.txt");
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			System.out.println(in.read());//98
			System.out.println(in.read());//98
			System.out.println(in.read());//180
			System.out.println(in.read());//243
			System.out.println(in.read());//205
			System.out.println(in.read());//245
			System.out.println(in.read());//13
			System.out.println(in.read());//10
			System.out.println(in.read());//54
			System.out.println(in.read());//-1
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

be careful:
1. In utf-8 mode, Chinese occupies 3 bytes; in GBK mode, Chinese occupies 2 bytes. The encoding method here is GBK.
2. Once the file is read, it outputs - 1(byte type) as the flag.
3. The content of the file is also output one byte at a time, converting ASCII code output.
4. You can replace the repeatedly read code with:

int b = -1;//Definition b makes sense
while((b = in.read()) != -1) {
	System.out.println(b);
}

(2) Read one byte array at a time

public class Test {
	public static void main(String[] args){
		File file = new File("test.txt");
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			//Define a byte array
			byte[] bs = new byte[3];
			//Define length to indicate the length of valid data read
			int length = 0;
			//in.read(byte[] byte) the return value is the number of valid bytes read,
			//When none, return - 1
			while((length = in.read(bs)) != -1) {
				//First way: output byte array directly
				System.out.println(Arrays.toString(bs));
				//The second way is to convert byte array to String and output data of String type
				String str = new String(bs);
//				String str1 = new String(bs,0,length);
				System.out.println(str);
//				System.out.println(str1);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}


explain:
(1) The second occurrence of - 48 is actually the first occurrence of - 48, because by - 46, there is no content to read, so - 48 is not covered.
(2) in.read(byte[] byte) the return value is the number of valid bytes read. If none of them is available, return - 1.
(3) When outputting as String type, if you change the code to:

in = new FileInputStream(file);
//Define a byte array
byte[] bs = new byte[3];
//Define length to indicate the length of valid data read
int length = 0;
while((length = in.read(bs)) != -1) {
//		String str = new String(bs);
		String str1 = new String(bs,0,length);
		//Mainly looking at the last line? No more
//		System.out.println(str);
		System.out.println(str1);
}


(3) Read as a whole according to the total byte length of the file

in = new FileInputStream(file);
byte[] bs = new byte[(int)file.length()];
in.read(bs);//Read the information from the file and store it in the byte array bs
//Convert byte array to string
String str = new String(bs);
System.out.println(str);

available(): can get the remaining bytes of the file at one time.

in = new FileInputStream(file);
int num = in.available();
byte[] bs = new byte[num];
in.read(bs);//Read the information from the file and store it in the byte array bs
//Convert byte array to string
String str = new String(bs);
System.out.println(str);

Comprehensive: copy and paste pictures

Read while writing.
1. Read and write byte by byte.
2. Read and write as an array of bytes.
If you specify the length of the byte array, you can take an integer multiple of 1024.

be careful:
When closing the current, follow the principle of opening first and then closing.

package day20200614;

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

public class Test {
	public static void main(String[] args) {
		try {
			FileInputStream in = new FileInputStream("src/day20200614/timg.jpg");
			FileOutputStream out = new FileOutputStream("src/day20200614/timg1.jpg");
			//Define a byte array
			byte[] bs = new byte[1024];
			//Define the effective byte length per read
			int length = 0;
			while((length = in.read(bs))!= -1) {
				//write in
				out.write(bs,0,length);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Topics: Java ascii encoding