Io (input and output) operations in java (1), iooutput

Source: Internet
Author: User

Io (input and output) operations in java (1), iooutput
IO, short for Input and Output. In java, IO involves a large range. Here we mainly discuss the reading and writing of file content.
Other knowledge points will be placed in subsequent chapters (I think the article is too long and no one has the patience to go to the end)

There are two main types of operations on file content:
They are:
  Ghost stream
  Byte stream
The volume stream has two abstract classes: Writer Reader.
The corresponding sub-classes FileWriter and FileReader can read and write files.
BufferedWriter and BufferedReader provide the buffer function to improve efficiency.
Likewise, a byte stream has two abstract classes: InputStream OutputStream.
Its corresponding sub-classes include FileInputStream and FileOutputStream for file read/write.
BufferedInputStream and BufferedOutputStream provide the buffer function

I made a lot of mistakes when I was learning IO, and some code on the Internet could not be compiled, or even the style was very different. Therefore, please note that:
1. The code in this article is long and should not be omitted, mainly because it is necessary to develop good coding habits as a newbie.
2. This Article is compiled in linux, which is similar to File. pathSeparator and File. separator. This representation is for cross-platform and robust considerations.
3. Some operations in the Code have multiple execution methods. I have adopted the method 1... method 2... expression, which can be compiled with just a few simple annotations.
4. the Code does not throw exceptions on the main method, but captures them separately, causing code to be too long. If you only test the code or do not want to have good programming habits, you can just throw it ......
5. There will be no repeated comments in similar functional areas. If the newbie cannot understand the following code, it must be that the above does not understand clearly.

Ghost stream
Instance 1: Writing streams
Copy codeThe Code is as follows:
Import java. io. File;
Import java. io. FileWriter;
Import java. io. IOException;
Public class Demo {
Public static void main (String [] args ){
// Create the path and name of the file to be operated
// File. separator indicates the system-related separator. in Linux, it is:/in Windows :\\
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
// Because IO operations throw an exception, the FileWriter reference is defined externally in the try statement block.
FileWriter w = null;
Try {
// Create a new FileWriter object using path
// Use the FileWriter (path, true) constructor to append data instead of overwrite data.
W = new FileWriter (path );
// Write the string to the stream. \ r \ n indicates a line break.
W. write ("Nerxious is a good boy \ r \ n ");
// If you want to see the write effect immediately, you need to call the w. flush () method.
W. flush ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
// If an exception occurs before, w objects cannot be generated.
// Therefore, make a judgment to avoid NULL pointer exceptions.
If (w! = Null ){
Try {
// Close the stream resource and capture exceptions again
W. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
}

After compilation, generate a file under the Directory and write the string

 
Instance 2: Reading the upstream stream
Copy codeThe Code is as follows:
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: read a single character
// Move one character unit down for each read
Int temp1 = r. read ();
System. out. println (char) temp1 );
Int temp2 = r. read ();
System. out. println (char) temp2 );
// Method 2: Read cyclically
// The read () method returns-1 after reading the object.
/*
While (true ){
Int temp = r. read ();
If (temp =-1 ){
Break;
}
System. out. print (char) temp );
}
*/
// Method 3: Simplified loop read Operations
// Read a single character. When temp is not equal to-1, the character is printed.
/* Int temp = 0;
While (temp = r. read ())! =-1 ){
System. out. print (char) temp );
}
*/
// Method 4: read into the character array
/*
Char [] buf = new char [1024];
Int temp = r. read (buf );
// Convert the array into a string for printing. The following parameter indicates
// If the character array is not full, other characters may appear at the end of the string after being converted to print.
// Therefore, the number of characters read is converted to a string.
System. out. println (new String (buf, 0, temp ));
*/
// Method 5: Read to character array optimization
// The size of the array to be defined cannot be determined because the file is too large.
// Therefore, it is generally defined that the array length is 1024 and is read cyclically.
/*
Char [] buf = new char [1024];
Int temp = 0;
While (temp = r. read (buf ))! =-1 ){
System. out. print (new String (buf, 0, temp ));
}
*/
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
If (r! = Null ){
Try {
R. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
}

Effect after compilation:


Example 3: copy a text file
Copy codeThe Code is as follows:
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: Writing in character array Mode
/*
Char [] buf = new char [1024];
Int temp = 0;
While (temp = r. read (buf ))! =-1 ){
W. write (new String (buf, 0, temp ));
}
*/
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
// Determine whether the pointer is null or not, and then close 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 compilation, copy the lrc.txt file under the lifeobject.


Example 4: Copy text files using the swap Stream Buffer
Copy codeThe Code is as follows:
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;
// Create a buffer reference
BufferedReader br = null;
BufferedWriter bw = null;
Try {
R = new FileReader (doc );
W = new FileWriter (copy );
// Create a buffer object
// Put the FileReader and FileWriter objects to improve efficiency 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;
// Read the row until null is returned.
// The readLine () method returns only the data before the linefeed.
While (line = br. readLine ())! = Null ){
// Write method using BufferWriter object
Bw. write (line );
// Wrap the line after writing the File Content
// The newLine () method depends on the platform
// In windows, the newline is \ r \ n.
// \ N in Linux
Bw. newLine ();
}
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
// The FileReader and FileWriter objects are no longer caught here
// 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
Instance 5: Writing of byte streams
Copy codeThe Code is as follows:
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 boy \ r \ n ";
Byte [] buf = str. getBytes ();
// You can also directly use o. write ("String". getBytes ());
// Because a string is an object, you can directly call the method.
O. write (buf );
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
If (o! = Null ){
Try {
O. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
}

To facilitate terminal display, add \ r \ n to the above compiled files
In fact, only \ n is used for line feed in linux.


Example 6: Reading byte streams
Copy codeThe Code is as follows:
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: read a single character
// Note that the test results are good in English.
// However, the Chinese language is tragic, but the following two methods have a good effect.
Int ch = 0;
While (ch = I. read ())! =-1 ){
System. out. print (char) ch );
}
// Method 2: Read the array cyclically
/*
Byte [] buf = new byte [1, 1024];
Int len = 0;
While (len = I. read (buf ))! =-1 ){
System. out. println (new String (buf, 0, len ));
}
*/
// Method 3: reading an array of the standard size
/*
// Set an array of just size
// Available () method returns the number of bytes of the object
// However, if the file is too large and the memory overflows, it will be a tragedy.
// Therefore, use it with caution !!! The above method is good.
Byte [] buf = new byte [I. available ()];
I. read (buf );
// Because the array size is good, you do not need to set the start 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 files to the terminal


Instance 7: copying binary files
Copy codeThe Code is as follows:
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 + "One Person ";
String copy = File. separator + "home" + File. separator + "siu" +
File. separator + "life" + File. separator + "one person's life ";
FileInputStream I = null;
FileOutputStream o = null;
Try {
I = new FileInputStream (bin );
O = new FileOutputStream (copy );
// Read and write files cyclically to complete copying
Byte [] buf = new byte [1, 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 ();
}
}
}
}
}

Replication effect,


Example 8: copying binary files using the byte stream buffer
Copy codeThe Code is as follows:
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 + "One Person ";
String copy = File. separator + "home" + File. separator + "siu" +
File. separator + "life" + File. separator + "one person's life ";
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 [1, 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 ();
}
}
}
}
}

The two directories have a life-saving file. By the way, this song is quite good.


When beginners learn to use the primary stream and word throttling, they will have no doubt: When should they use the primary stream and when should they use the byte stream?

As a matter of fact, you should know that the so-called ghost stream must be used for operations similar to text files or character files.
Byte streams operate on binary files that cannot directly obtain text information, such as video clips, mp3 files, and video files.
To put it bluntly, it is stored in bytes on the hard disk, but the compaction stream is more convenient on the operating text.
In addition, why should we use the buffer zone?

We know that downloading software such as Thunder has a cache function, and the hard disk itself has a buffer.
Think about it. If data is read and written, regardless of the size of the data, it will inevitably cause a great burden on the hard disk and it will feel uncomfortable.
The same is true for people. If you don't want to eat a meal at a time, feed a spoonful every minute. What do you think?
Therefore, using a buffer can effectively improve efficiency when reading and writing large files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.