Summary of IO (input and output) operations in Java (i) _java

Source: Internet
Author: User
Tags array length flush readline
The so-called IO, which is the abbreviation of input and output. In Java, IO involves a relatively large scope, which focuses on reading and writing about file content
Other knowledge points will be placed in subsequent chapters (I think, the article is too long, no one has the patience to turn to the end)

the operation of the contents of the file is mainly divided into two categories
respectively:
   character Streams
   Byte stream
Where there are two abstract classes of character streams: Writer Reader
Its corresponding subclass FileWriter and FileReader can realize the read-write operation of files
BufferedWriter and BufferedReader can provide buffer functionality to improve efficiency
Similarly, a byte stream has two abstract classes: InputStream OutputStream
Its corresponding subclass has FileInputStream and FileOutputStream to implement file read and write
Bufferedinputstream and Bufferedoutputstream provide buffer functionality

I learned IO when I made a lot of confusion, some of the code online can not be compiled, and even style are very different, so novice please note
1. This article is longer, should not be omitted omitted, mainly because as a novice need to develop good code writing habits
2. This article is compiled under Linux, similar to File.pathseparator and File.separator, for cross-platform and robust considerations
3. Some of the operations in the code have a variety of ways to execute, I adopted the mode 1 ... Mode 2 ... , you can compile it simply by gently unlocking the annotation
4. The code does not throw an exception on the main method, but separately capture, resulting in too long code, if only testing, or do not want to have good programming habits, then you casually throw it ...
5. The function similar place does not write the annotation repeatedly, if the novice does not understand the following code, that certainly is above does not understand clearly

character Streams
Instance 1: Writing of character streams
Copy Code code as follows:

Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
public class Demo {
public static void Main (string[] args) {
Create a file path and name to manipulate
where File.separator represents system-related delimiters, Linux is:/Windows below: \
String Path = file.separator + "Home" + File.separator + "SIU" +
File.separator + "Work" + File.separator + "Demo.txt";
Because an IO operation throws an exception, the FileWriter reference is defined outside the TRY statement block
FileWriter w = null;
try {
Create a new FileWriter object with path
If you need to append data instead of overriding, use the FileWriter (path,true) construct method
w = new FileWriter (path);
Writes a string to the stream, \ r \ n indicates a newline. Want to have a good
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 earlier, then the W object cannot be generated
So to make a judgment, to avoid null pointer anomalies
if (w!= null) {
try {
To turn off streaming resources, you need to catch exceptions again
W.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
}
}

After compiling, generate the file under the directory and write the string


Instance 2: Reading of character streams

Copy Code code 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);
Way one: read a single character in a way
Move down one character unit at a time per read
int temp1 = R.read ();
System.out.println ((char) TEMP1);
int temp2 = R.read ();
System.out.println ((char) TEMP2);
Mode two: Loop read
The Read () method reads to the end of the file and returns-1
/*
while (true) {
int temp = R.read ();
if (temp = = 1) {
Break
}
System.out.print ((char) temp);
}
*/
Mode three: Simplified operation of cyclic reading
Single character read, print characters when temp is not equal to-1
/*int temp = 0;
while (temp = R.read ())!=-1) {
System.out.print ((char) temp);
}
*/
Mode four: Read into the character array
/*
char[] buf = new char[1024];
int temp = R.read (BUF);
Converts an array to a string print, and the following argument means
If the character array is not full, it will be converted to a string. Other characters may appear at the tail
So how many characters are read and how many are converted into strings
System.out.println (New String (buf,0,temp));
*/
Mode five: Read into the optimization of the character array
Because sometimes the file is too large to determine the size of the array that needs to be defined
So the general definition of the array length is 1024, read in a circular way
/*
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 ();
}
}
}
}
}

The effect after compilation:


Example 3: Copying a text file

Copy Code code 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);
Mode one: Single character write
int temp = 0;
while (temp = R.read ())!=-1) {
W.write (temp);
}
Mode two: Character Array way write
/*
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 {
Judge the null pointer reference separately, 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 compiling, produces the Lrc.txt file in the life directory, the replication succeeds


Example 4: Copying a text file with a buffer of character streams

Copy Code code 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 reference to a buffer
BufferedReader br = null;
BufferedWriter bw = NULL;
try {
R = new FileReader (DOC);
w = new FileWriter (copy);
Creating a Buffer Object
Put FileReader and FileWriter objects that need to be more efficient into their constructors
Of course, you can also use the way of anonymous objects br = new BufferedReader (new FileReader (DOC));
br = new BufferedReader (r);
BW = new BufferedWriter (w);
String line = null;
Read rows until NULL is returned
The ReadLine () method returns only the data before the line feed
while (line = Br.readline ())!= null) {
Using the Write method of the Bufferwriter object
Bw.write (line);
Wrapping a line after you finish writing the contents of the file
NewLine () method depends on platform
The line break under Windows is \ r \ n
Linux is \ n
Bw.newline ();
}
catch (IOException e) {
E.printstacktrace ();
finally {
You no longer need to catch exceptions for FileReader and FileWriter objects here
Closing a buffer is the flow object in the closed buffer
if (br!= null) {
try {
R.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
if (BW!= null) {
try {
Bw.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
}
}

Word throttling
Instance 5: Writing of a byte stream
Copy Code code 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 use O.write ("String". GetBytes ()) directly.
Because a string is an object, you can call the method directly
O.write (BUF);
catch (IOException e) {
E.printstacktrace ();
finally {
if (o!= null) {
try {
O.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
}
}

Files generated after compilation, above in the string plus \ r \ n is to facilitate the terminal display
In fact, under Linux, line wrapping only \ n can


Example 6: Reading a byte stream

Copy Code code 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);
Way one: Single character read
It should be noted that here I use English text to test the effect is good
But the Chinese tragedy, but the following two methods are good
int ch = 0;
while ((Ch=i.read ())!=-1) {
System.out.print ((char) ch);
}
Mode two: Array loop read
/*
byte[] buf = new byte[1024];
int len = 0;
while (len = I.read (buf))!=-1) {
System.out.println (New String (Buf,0,len));
}
*/
Mode three: The standard size of array reads
/*
Set an array of just the size
Available () method returns the number of bytes in the file
However, if the file is too large and memory overflows, it's a tragedy.
So, be careful with!!! That's a good way up there.
byte[] buf = new byte[i.available ()];
I.read (BUF);
Because the array size is just right, you do not have to set the starting point in the constructor to convert 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 Terminal


Instance 7: Replication of binary files

Copy Code code 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 + "a person lives. mp3";
String copy = File.separator + "Home" + File.separator + "SIU" +
File.separator + "Life" + File.separator + "a person living. mp3";
FileInputStream i = null;
FileOutputStream o = null;
try {
i = new FileInputStream (BIN);
o = new FileOutputStream (copy);
Read and write the file in a circular way to complete the replication
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 effects, as shown in figure:


Example 8: Replication of binary files using a byte stream buffer

Copy Code code 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 + "a person lives. mp3";
String copy = File.separator + "Home" + File.separator + "SIU" +
File.separator + "Life" + File.separator + "a person living. 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 ();
}
}
}
}
}

Two directories have a "one person living. mp3" File, by the way, this is a nice song.


When beginners learn to use character streams and byte streams, there is a question: when should the character stream be used, and when should it be used?

In fact, think about it should be known, the so-called character stream, is definitely used to manipulate similar text files or with character files of the occasion more
and the byte stream is the operation of those who can not directly get text information binary files, such as pictures, MP3, video files, etc.
Plainly on the hard disk are stored in bytes, but the character stream is more convenient to manipulate the text above
In addition, why use the buffer?

We know, such as the Thunderbolt download software has a caching function, the hard disk itself also has a buffer
Imagine, if a data, regardless of the size of the beginning to read and write, will cause a heavy burden on the hard drive, it will feel very uncomfortable
People are not the same, a meal does not let you eat at a time, feed a spoonful every minute, how do you think?
Therefore, using buffer can effectively improve the 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.