The Io of input and output operations in Java summarize the of one

  • 2020-04-01 01:21:58
  • OfStack

IO is short for Input and Output. In Java, IO covers a wide range of topics, and this section focuses on reading and writing to the contents of a file
Other knowledge points will be followed by chapters (too long, I think, for anyone to turn to the end)

Operations on the contents of a file fall into two main categories
Respectively is:
Characters of the flow
Byte stream
There are two abstract classes for the character stream: Writer Reader
Its corresponding subclasses FileWriter and FileReader can implement file read and write operations
BufferedWriter and BufferedReader can provide buffer function to improve efficiency
There are also two abstract classes for byte streams: InputStream OutputStream
The corresponding subclasses are FileInputStream and FileOutputStream
The BufferedInputStream and BufferedOutputStream provide buffer functionality

I made a lot of confusion when I was learning IO, some of the code on the Internet can not be compiled, even the style is very different, so novice please pay attention :
1. The code in this paper is long and should not be omitted, mainly because a novice needs to develop good code writing habits
2. This article is compiled under Linux. Expressions like file.pathseparator and file.separator are used for cross-platform and robustness reasons
3. Some operations in the code can be executed in multiple ways. Methods 2... , which can be compiled by simply undoing the comments
4. Instead of throwing exceptions on the main method, the code is caught separately, causing the code to be too long.
5. Similar functions are not repeated to write comments, if the novice does not understand the following code, it must be the above did not understand clearly

Characters of the flow
Example 1: write to a stream of characters
 
import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 
public class Demo { 
public static void main(String[] args ) { 
//Create the file path and name to operate on
//Where file.separator represents the system-related separator, Linux: / Windows: \
String path = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + "demo.txt"; 
//Because the IO operation throws an exception, a reference to the FileWriter is defined outside the try block
FileWriter w = null; 
try { 
//Create a new FileWriter object with path as the path
//If you need to append data rather than overwrite it, use the FileWriter (path, true) constructor
w = new FileWriter(path); 
//Writes the string to the stream, rn means that the newline is good
w.write("Nerxious is a good boyrn"); 
//If you want to see the write effect immediately, you need to call the w.lush () method
w.flush(); 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
//If an exception occurs earlier, the w object cannot be generated
//So make a decision to avoid null pointer exceptions
if(w != null) { 
try { 
//Close the stream resource and you need to catch the exception again
w.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

After compiling, generate the file under the directory and write the string & PI;

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201301/201301101002518.png ">  
Instance 2: read of a stream of characters

 
import java.io.File; 
import java.io.FileReader; 
import java.io.IOException; 
public class Demo2 { 
public static void main(String[] args ) { 
String path = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + "demo.txt"; 
FileReader r = null; 
try { 
r = new FileReader(path); 
//Method 1: a way to read a single character
//Move down one character unit per read
int temp1 = r.read(); 
System.out.println((char)temp1); 
int temp2 = r.read(); 
System.out.println((char)temp2); 
//Method 2: loop read
//The read() method returns -1 at the end of the file
 
//Mode 3: simplified operation of loop reading
//Single character read and print when temp is not equal to -1
 
//Method 4: read into the array of characters
/* 
char[] buf = new char[1024]; 
int temp = r.read(buf); 
//Converts an array to a string to print
//If the array of characters is not full, other characters may appear at the end of the printout converted to a string
//Therefore, as many characters are read, so many are converted into strings
System.out.println(new String(buf,0,temp)); 
*/ 
//Method 5: read into the optimization of the character array
//Sometimes the file is too large to determine the size of the array that needs to be defined
//Therefore, the length of the array is generally defined as 1024 and read in a loop
 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
if(r != null) { 
try { 
r.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

Effect after compilation:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201301/201301101002519.png ">
Example 3: copy of a text file

 
import java.io.File; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
public class Demo { 
public static void main(String[] args ) { 
String doc = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + "demo.txt"; 
String copy = File.separator + "home" + File.separator + "siu" + 
File.separator + "life" + File.separator + "lrc.txt"; 
FileReader r = null; 
FileWriter w = null; 
try { 
r = new FileReader(doc); 
w = new FileWriter(copy); 
//Method 1: write a single character
int temp = 0; 
while((temp = r.read()) != -1) { 
w.write(temp); 
} 
//Method 2: write the array of characters
 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
//Each determines whether a null pointer reference is present, and then closes the stream
if(r != null) { 
try { 
r.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
if(w != null) { 
try { 
w.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

After compiling, produce the life directory under the lrc.txt file, copy successfully

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201301/2013011010025110.png ">
Example 4: using the buffer of the character stream to copy the text file

 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
public class Demo { 
public static void main(String[] args ) { 
String doc = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + "demo.txt"; 
String copy = File.separator + "home" + File.separator + "siu" + 
File.separator + "life" + File.separator + "lrc.txt"; 
FileReader r = null; 
FileWriter w = null; 
//Creates a reference to the buffer
BufferedReader br = null; 
BufferedWriter bw = null; 
try { 
r = new FileReader(doc); 
w = new FileWriter(copy); 
//Create buffer object
//Put the FileReader and FileWriter objects that need to be more efficient into their constructors
//Of course, you can also use the anonymous object method br = new BufferedReader(new FileReader(doc));
br = new BufferedReader(r); 
bw = new BufferedWriter(w); 
String line = null; 
//Reads the row until null is returned
//The readLine() method returns only the data before the newline
while((line = br.readLine()) != null) { 
//Use the write method of the BufferWriter object
bw.write(line); 
//After writing the contents of the file, break the line
//The newLine() method is platform-specific
//The newline in Windows is rn
//For Linux it's n
bw.newLine(); 
} 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
//You no longer need to catch exceptions for FileReader and FileWriter objects
//Closing the buffer is to close the stream object in the buffer
if(br != null) { 
try { 
r.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
if(bw != null) { 
try { 
bw.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

Byte stream
Example 5: write to a byte stream
 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
public class Demo { 
public static void main(String[] args ) { 
String path = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + "demo.txt"; 
FileOutputStream o = null; 
try { 
o = new FileOutputStream(path); 
String str = "Nerxious is a good boyrn"; 
byte[] buf = str.getBytes(); 
//You can also directly use o.rite ("String". GetBytes ());
//Because a string is just an object, you can call methods directly
o.write(buf); 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
if(o != null) { 
try { 
o.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

After compiling the resulting file, the above added \r\n to the string is to facilitate the terminal display
In fact, just use \n for line breaks under Linux

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201301/2013011010025111.png ">
Example 6: byte stream read

 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
public class Demo { 
public static void main(String[] args ) { 
String path = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + "demo.txt"; 
FileInputStream i = null; 
try { 
i = new FileInputStream(path); 
//Method 1: single character read
//It is important to note that here I test well with English text
//Chinese is a tragedy, but the following two methods work well
int ch = 0; 
while((ch=i.read()) != -1){ 
System.out.print((char)ch); 
} 
//Method 2: array loop read
 
//Method 3: standard size array read
/* 
//Make an array of exactly the right size
//The available() method returns the number of bytes in the file
//However, if the file is too large and memory runs out, that's a tragedy
//So dear friends should be used with caution!! The above method is good
byte[] buf = new byte[i.available()]; 
i.read(buf); 
//Because the array is just the right size, there is no need to set the starting point in the constructor when converting to a string
System.out.println(new String(buf)); 
*/ 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
if(i != null) { 
try { 
i.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

Read the file to the terminal

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201301/2013011010025112.png ">
Example 7: copying binary files

 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
public class Demo { 
public static void main(String[] args ) { 
String bin = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + " Live alone .mp3"; 
String copy = File.separator + "home" + File.separator + "siu" + 
File.separator + "life" + File.separator + " Live alone .mp3"; 
FileInputStream i = null; 
FileOutputStream o = null; 
try { 
i = new FileInputStream(bin); 
o = new FileOutputStream(copy); 
//Loop in the write out file to complete the copy
byte[] buf = new byte[1024]; 
int temp = 0; 
while((temp = i.read(buf)) != -1) { 
o.write(buf, 0, temp); 
} 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
if(i != null) { 
try { 
i.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
if(o != null) { 
try { 
o.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

Copy the effect, as shown:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201301/2013011010025113.png ">
Example 8: copying binary files using the buffer of a byte stream

 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
public class Demo { 
public static void main(String[] args ) { 
String bin = File.separator + "home" + File.separator + "siu" + 
File.separator + "work" + File.separator + " Live alone .mp3"; 
String copy = File.separator + "home" + File.separator + "siu" + 
File.separator + "life" + File.separator + " Live alone .mp3"; 
FileInputStream i = null; 
FileOutputStream o = null; 
BufferedInputStream bi = null; 
BufferedOutputStream bo = null; 
try { 
i = new FileInputStream(bin); 
o = new FileOutputStream(copy); 
bi = new BufferedInputStream(i); 
bo = new BufferedOutputStream(o); 
byte[] buf = new byte[1024]; 
int temp = 0; 
while((temp = bi.read(buf)) != -1) { 
bo.write(buf,0,temp); 
} 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
if(bi != null) { 
try { 
i.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
if(bo != null) { 
try { 
o.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 
} 

Both catalogs have "one life.mp3," which, by the way, is a great song to listen to

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201301/2013011010025114.png ">
After learning to use character streams and byte streams, beginners may wonder when to use character streams and when to use byte streams.

In fact, if you think about it carefully, you should know that the so-called character stream is definitely used to operate on situations like text files or with character files
A byte stream operates on binary files that do not have direct access to text information, such as images, mp3s, and videos
Basically, it is stored in bytes on the hard disk, but the stream of characters is more convenient for manipulating text
Besides, why use buffers?

We know that downloadable software like thunderbolt has a cache, and the hard drive itself has a buffer
Imagine that if you start reading and writing data as soon as you have it, no matter how big or small, you're going to put a lot of strain on your hard drive, and it's going to feel bad
People are not the same, a meal does not let you eat all at once, every minute to feed a spoonful, what do you think?
Therefore, using buffers can effectively improve the efficiency of reading and writing large files


Related articles: