current position:Home>Java object oriented -- IO stream

Java object oriented -- IO stream

2022-01-26 22:58:03 #HashMap#

We meet again , It's been a tough week , Just finished learning file and IO flow , I believe many Xiaobai heard IO The scalp becomes numb when it flows , But that's how the subject came , I looked too high at the teacher before 300 Set , At that time, Mr. Pei said , As a beginner, learning is simply dissuading , I want to swear , I've learned recently IO In retrospect , Mr. Pei is really good , about IO Let me share my learning experience with you , The underlying principles only need to be familiar with , Rarely used , Unless you're the boss of bottom development .

1.File class

1.1 about File Class, we just need to simply master the creation of files , Directory creation and File The basic method of class
Definition :File Represents an abstract representation of file and directory pathnames
1.2 Absolute path and relative path
i) Absolute path : Simply put, the path with drive letter (E:/test)
ii) Relative paths : Then the relative path without drive letter

/* * With "E:/test/a.txt" File as an example  */
File file = new File("E:/test/a.txt");// Absolute path 
file = new File("a.txt");// Relative paths 

1.3 Common methods

File file = new File("E:/test/a.txt");// Create the object under the path 
System.out.println(file.separator);// Print slashes 
System.out.println(file.pathSeparator);// Print semicolons 
System.out.println(file.getName());// Get the name 
System.out.println(file.getAbsolutePath());// Get absolute path 
System.out.println(file.exists());// Does the file exist 
System.out.println(file.isFile());// Is it a document 
System.out.println(file.isDirectory());// Is it a directory 
System.out.println(file.mkdirs());// Whether to create a directory 
System.out.println(file.createNewFile());// Whether the file was created successfully , The creation failed or the file itself exists as false

1.4 Create files and directories

/* * Many people think at first File file = new File("E:/test/a.txt"); * The file has been successfully created , Is really just new The object , You also need to use the corresponding command ( Method ) */
File file = new File("E:/test/a.txt");// Create the object under the path 
file.mkdir();// Create a directory first 
file.createNewFile();// Create the file again 

1.5 Use recursion to print all files

public class Test005File {
    
	public static void main(String[] args) {
    
		printName(new File("src"));// Recursively call 
	}
	public static void printName(File src){
    
		if(null==src){
    // Judge not empty 
			return;
		}
		if(!src.exists()){
    // If there is no file, do not print 
			return;
		}
		System.out.println(src.getName());// Print the name of the directory 
		if(src.isDirectory()){
    
			File[] file = src.listFiles();// Store the file name in the file array 
			for(File temp:file){
    // enhance for Loop traversal 
				printName(temp);
			}
		}
	}
}

2.IO flow

2.1 speak IO Before streaming, let's take a picture , Can help you understand their relationship , It's a little small, but it's clear when you open it

 Insert picture description here
For reading data ( Pure text ), Create an array of bytes , Put the bytes into the byte array , Then convert the byte array into a string , So the byte stream needs to be from the byte array -> character string , And for character streams , It is itself a character , Therefore, there is no need to convert , Take byte input stream as an example , At the bottom is the node flow (FileInputStream), The rest are processing streams (BufferedInputStream), To put it bluntly, processing flow is used to package , Decorated , Can improve the efficiency of the code , But the final processing is the node flow ., Here are some typical input and output streams
stay IO You only need to master four steps in the stream, which can help you quickly understand and read , Write operation
i) Create source
ii) Select flow
iii) Operational data
iiii) close resource

2.2 FileInputStream

/* *  Read text with byte array FileInputStream( use try catch finally Capture exception ) * 1. Create source  * 2. Select flow  * 3. operation  * 4. close resource  * */
public class Test004FileInputStream {
    
	public static void main(String[] args) {
    
		//1. Create source 
		File file = new File("test1/a.txt");
		//2. Select flow 
		InputStream is=  null;
		try {
    
			is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
    
			e.printStackTrace();
		}
		//3. operation 
		byte[] bs = new byte[1024];
		try {
    
			while(-1!=is.read(bs)){
    
				System.out.println(new String(bs));
			}
		} catch (IOException e) {
    
			e.printStackTrace();
		}finally{
    
			try {
    
		//4. close resource 
				is.close();
			} catch (IOException e) {
    
				e.printStackTrace();
			}
		}
	}
}

2.3 FileOutputStream

/* *  Write out with a byte array  FileOutputStream * */
public class Test005FileOutputStream {
    
	public static void main(String[] args) {
    
		//1. Create source 
		File file = new File("test1/a.txt");
		//2. Select flow 
		OutputStream os = null;
		try {
    
			os = new FileOutputStream(file);
		//3. operation 
			String str = new String("hello i want to play a game");
			byte[] bs = str.getBytes();// Converts a string to a byte array 
			os.write(bs);// Write data 
			os.flush();// Refresh 
		} catch (IOException e) {
    
			e.printStackTrace();
		}finally{
    
			try {
    
		//4. close resource 
				os.close();
			} catch (IOException e) {
    
				e.printStackTrace();
			}
		}
	}
}

2.4 BufferedInputStream( Cache stream , Improve efficiency )

/* * BufferedInputStream( Processing flow ) Is in FileInputStream Put a layer on the foundation  * */
public class Test006BufferedInputStream {
    
	public static void main(String[] args) {
    
		//1. Create source 
		File file = new File("test1/a.txt");
		//2. Select flow 
		InputStream is = null;// Using cache stream is more efficient for code 
		try {
    
			is = new BufferedInputStream(new FileInputStream(file));
		//3. operation 
			byte[] bs = new byte[1024];// Create an array of bytes 
			while(-1!=is.read(bs)){
    // At the end of the file len=-1
				System.out.println(new String(bs));
			}
		} catch (IOException e) {
    
			e.printStackTrace();
		}finally{
    
			try {
    
		//4. close resource 
				is.close();
			} catch (IOException e) {
    
				e.printStackTrace();
			}
		}
	}
}

2.5 BufferedReader

/* * BufferedReader( Processing flow ) decorate FileReader( Node flow ) * */
public class Test007BufferedReader {
    
	public static void main(String[] args) {
    
		//1. Create source 
		File file = new File("test1/a.txt");
		//2. Select flow 
		BufferedReader br = null;
		try {
    
		//3. operation 
			br = new BufferedReader(new FileReader(file));
			String str = br.readLine();//BufferedReader Yes readLine Method 
			System.out.println(str);
		} catch (IOException e) {
    
			e.printStackTrace();
		}finally{
    
			try {
    
		//4. close resource 
				br.close();
			} catch (IOException e) {
    
				e.printStackTrace();
			}
		}
	}
}

2.6 InputStreamReader( Converted flow )

Used to solve FileInputStream Conversion is troublesome , and FileReader Possible garbled code

/* *  use FileInputStream You need to convert the byte array to a string , More trouble , use FileReader Because the character set cannot be specified , There will be garbled code  *  So we consider using the transformation stream InputStreamReader *  byte -> String can specify the encoding method  *  character string -> Bytes cannot be specified  */
public class Test008InputStreamReader {
    
	public static void main(String[] args) throws IOException{
    
		//FileInputStream
		File file = new File("test1/a.txt");
		InputStream is = new FileInputStream(file);
		byte[] bs = new byte[1024];
		int len = is.read(bs);
		System.out.println(new String(bs,0,len,"utf-8"));// You can specify the character set ( Encoding mode ), But you need a byte array -> character string , trouble 
		//FileReader
		Reader r= new FileReader(file);
		char[] ch = new char[1024];
		len = r.read(ch);
		System.out.println(new String(ch,0,len));// Cannot specify character set ( Encoding mode ), It's already a character array , You don't have to convert it to a string 
		//InputStreamReader
		Reader isr = new InputStreamReader(new FileInputStream(file),"utf-8");
		len = isr.read(ch);
		System.out.println(new String(ch,0,len));
	}
}

summary : In fact, as long as you master the byte stream, you can know how to write the character stream , The rest of the processing flow only needs to be set on the basis of node flow , But the code is to knock , No matter how difficult or simple, you still need to knock . other IO The original code of the stream
IO Stream source code ( Extraction code :8o3i)

3.Commons-io

3.1 It's not easy to see the little friends here , In fact, the above is the underlying principle , We just need to be familiar and understand , In fact, we usually use something like commons-io This kind of tools to operate on files , Is it a lot easier to see here , Such tools can achieve most functions , This utility class is used to handle filenames ( File path ) Of , It can easily solve the problem of different file name specifications for different operating systems , The methods inside are static , Call directly with class , In this way, there is a connection to download

Finally, if you need other source code or software, you can confide in me , We can learn together
commons-io2.6 download ( Extraction code :lopz)

copyright notice
author[#HashMap#],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262257594125.html

Random recommended