preface

In my last article, I reviewed multithreading in Java. This article mainly introduces the Java IO related knowledge.

The introduction of the IO

What is IO?

The IO name is the abbreviation of Input and Output, which is the Input stream and Output stream. The input stream is used to read data from the source and the output stream is used to write data to the destination.

You can get an idea of the IO flow from the following example diagram:

IO flow using

IO stream operations on files are divided into character stream and byte stream.

Characters of the flow

The character stream has two abstract classes: Writer and Reader. The subclasses FileWriter and FileReader can be used to read and write files. BufferedWriter and BufferedReader can provide buffering capabilities to improve efficiency.

I remember not long after I started learning Java, I used character streams in tutorials to read and write characters. It’s more common to run a main method and then type the characters in the console, get the input characters and do some logic control and so on. For example, enter characters on the console, enter quit, and enter other characters to print.

Code examples:

	public static void main(String[] args)  {
		try {
			test(a); } catch (IOException e) { e.printStackTrace(); } } private static voidtest() throws IOException { String str; Br = new BufferedReader(new InputStreamReader(system.in)); System.out.println("Enter the character 'quit'."); // Read charactersdo {
		       str=br.readLine();
		       System.out.println("The character you entered is :"+str);
		    } while(! str.equals("quit"));
			 br.close();
	}
Copy the code

Then we enter Hello and quit. The results are as follows:

Input character, input'quit'To exit. Hello you have entered the following character :quit Hello you have entered the following character :quitCopy the code

Using the above example, we can briefly understand the character stream. In general, we mostly use character streams to read and write files, mostly text files, such as.txt files. Here we also incidentally introduce how to use.

Code examples:

/** ** Write and read files * @throws IOException */ private static voidtest2() throws IOException {// Create the file path and name to operate. String path ="E:/test/hello.txt";
        String str="hello world";
        FileWriter fw = new FileWriter(path);  
        fw.write(str);  
        fw.close();  
        
        FileReader fr = new FileReader(path);  
        StringBuffer sb=new StringBuffer();
  		while(fr.ready()){
  			sb.append((char)fr.read());
  		}
        System.out.println("Output."+sb.toString());
        fr.close();
	}

Copy the code

Note: If you are running on a different system, you can use the file. separator method, which represents the system separator.

Output result:

Output: hello wordCopy the code

In the above code examples, we use FileWriter and FileReader to read and write files. Although characters can be written and read, the efficiency is not high, because it is direct reading and writing to disk. Usually for reading and writing files, we use buffering. The advantage of using buffering is similar to dumping garbage, which is sorted and piled up and then discarded when it reaches a certain size, rather than just dumping a little garbage once.

Add BufferedWriter and BufferedReader classes to the above code for buffering.

Code examples:

/** * Write and read files * @throws IOException */ private static voidtest3() throws IOException {// Create the file path and name to operate. String path ="E:/test/hello.txt";
        String str="Hello!";
        FileWriter fw = new FileWriter(path);  
        BufferedWriter bw=new BufferedWriter(fw);
        bw.write(str);  
        bw.close();
        fw.close();  
        
        FileReader fr = new FileReader(path);  
        BufferedReader br=new BufferedReader(fr);
        StringBuffer sb=new StringBuffer();
  		while(br.ready()){
  			sb.append((char)br.read());
  		}
        System.out.println("Output."+sb.toString());
        br.close();
        fr.close();
	}
Copy the code

Note: It is important to note the order of closing, closing the buffer first, then closing the file.

Byte stream

Byte streams also have two abstract classes: InputStream and OutputStream. Its corresponding subclasses include FileInputStream and FileOutputStream to implement file read and write operations. BufferedInputStream and BufferedOutputStream provide buffer functionality

Byte stream can also read text, but its main use is to read binary files that cannot directly access text information, such as music files, video files, image files, and so on. Here we’re still reading and writing to the file, but we’re adding ‘hello’ to the new file from what we wrote in hello.txt. Since Chinese is used here, the encoding needs to be set accordingly.

Code examples:

/** * Create a file and read records * @throws IOException */ private static voidtest4() throws IOException {
		String path="E:/test/hello.txt";
		String path2="E: / test/hello. TXT";
		String str="Hello!"; InputStream input = new FileInputStream(path); InputStreamReader reader = new InputStreamReader(input,"UTF-8");
	    StringBuffer sb=new StringBuffer();
		while(reader.ready()){ sb.append((char)reader.read()); } input.close(); reader.close(); OutputStream output = new FileOutputStream(path2); // Create a file and write data to it. OutputStreamWriter writer = new OutputStreamWriter(output,"UTF-8"); writer.write(sb+str); writer.close(); output.close(); InputStream input2 = new FileInputStream(path2); InputStreamReader reader2 = new InputStreamReader(input2,"UTF-8");
	    StringBuffer sb2=new StringBuffer();
		while(reader2.ready()){
			sb2.append((char)reader2.read());
		}
		System.out.println("Output."+sb2);
		input2.close();
		reader2.close();
	}	
Copy the code

Results:

Output: Hello world!Copy the code

You can see that the results are in line with our expectations.

File

In learning about IO streams, we’ll also touch on the File class. The File class is dominated by operations on folders. For example, folder creation, deletion, view and so on. Here we will briefly introduce the related use of File class, or use code with comments to illustrate.

Code examples:

private static void test5() throws IOException {
		String path="E:/test/test2";
		String path2="E:/test/test3/test3";
		String path3="E:/test/test2/test2.txt"; File f = new File(path); File f2 = new File(path2); File f3 = new File(path3); // Create folder system.out.println ("="+f.mkdir()); // Create folders and all parent folders system.out.println ("= ="+f2.mkdirs()); // Create a text system.out.println ("= = ="+f3.createNewFile()); // Get the name system.out.println ("= = ="+f3.getName()); // Get the parent name system.out.println ("= = ="+f3.getParent()); // Get the current path system.out.println ("= = ="+f3.getPath()); System.out.println(system.out.println ("= ="+f2.isDirectory());
		System.out.println("= = ="+f3.isDirectory()); // Delete the file system.out.println ("= = ="+f3.delete());	
}	
Copy the code

Output result:

=true= =true= = =true= = =test2.txt
===E:\test\test2
===E:\test\test2 \test2.txt
==true= = =false= = =true
Copy the code

The File class is only a brief introduction, the specific use of the need to configure the actual scenario. Note that when creating or deleting a file, check whether the file exists first. Otherwise, an exception will be thrown.

other

That’s the end of this article, thank you for reading! Welcome to comment and like, your support is my biggest motivation to write!

Copyright Notice: Author: nothing Blog garden reference: http://www.cnblogs.com/xuwujing CSDN reference: http://blog.csdn.net/qazwsxpcm personal blog reference: http://www.panchengming.com