Implementation of the Java IO file copy Function
To copy an object, you can use either of the following methods:
Method 1: Read the content of all files to the program at one time and then output them at one time. In this way, you need to enable a data of the same size as the file for temporary saving of the data, but when the file is too large? Will the program collapse? Welcome to try ^ @ ^.
Method 2: Use the read and write operations, which improves the efficiency and will not occupy too much memory space.
Therefore, we adopt the second method to read and write while reading.
Package signal. IO;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileOutputStream; import java. io. IOException;
Import java. io. InputStream;
Import java. io. OutputStream;
Public class CopyFile {
/**
* Define a method to copy objects.
*
* @ Param src Source File Path
* @ Param target file path
* @ Throws IOException
*/
Public static void CopyFile (File src, File target) throws IOException {
/**
* Verify whether the source file exists.
*/
If (! Src. exists ()){
System. err. println ("There is no such a file !!! ");
System. exit (1 );
}
/**
* Verify whether the target path exists. If not, create a parent path.
*/
If (! Target. getParentFile (). exists ()){
Target. getParentFile (). mkdirs ();
}
Int temp = 0; // indicates whether the source file is read to the end.
InputStream input = new FileInputStream (src );
OutputStream output = new FileOutputStream (target );
While (temp = input. read ())! =-1 ){
Output. write (temp );
}
Input. close ();
Output. close ();
}
Public static void main (String [] args ){
String in = "C :\\ Users \ Administrator \ Desktop \ tmp.txt"; // source file path
String out = "C :\\ Users \ Administrator \ Desktop \ tmp_copy.txt"; // target path (you can rename it at this time)
File src = new File (in );
File target = new File (out );
Try {
CopyFile (src, target );
System. out. println ("Copy Successfully! ");
} Catch (IOException e ){
System. err. println ("ERROR: Something wrong while copying! ");
E. printStackTrace ();
}
}
}
As written in the code, we read and write data. The source code of the read () method used is as follows:
...
/**
* Reads the next byte of data from the input stream. The value byte is
* Returned as an <code> int </code> in the range <code> 0 </code>
* <Code> 255 </code>. If no byte is available because the end of the stream
* Has been reached, the value <code>-1 </code> is returned. This method
* Blocks until input data is available, the end of the stream is detected,
* Or an exception is thrown.
*
* <P> A subclass must provide an implementation of this method.
*
* @ Return the next byte of data, or <code>-1 </code> if the end of
* Stream is reached.
* @ Exception IOException if an I/O error occurs.
*/
Public abstract int read () throws IOException;
...
"@ Return the next byte of data, or-1 if the end of the stream is reached. ", when the returned value of the read () method is"-1 ", the file is read completely. As a result, it is not difficult to explain:
While (temp = input. read ())! =-1 ){
Output. write (temp );
}
With this foundation, we can improve the reading and writing of one byte at a time. Version 2 is as follows:
Package signal. IO;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. OutputStream;
Public class CopyFileVersion2 {
/**
* Define a method to copy objects.
*
* @ Param src Source File Path
* @ Param target file path
* @ Throws IOException
*/
Public static void CopyFile (File src, File target) throws IOException {
/**
* Verify whether the source file exists.
*/
If (! Src. exists ()){
System. err. println ("There is no such a file !!! ");
System. exit (1 );
}
/**
* Verify whether the target path exists. If not, create a parent path.
*/
If (! Target. getParentFile (). exists ()){
Target. getParentFile (). mkdirs ();
}
Int temp = 0;
Byte data [] = new byte [1024]; // read 1024 bytes each time
InputStream input = new FileInputStream (src );
OutputStream output = new FileOutputStream (target );
While (temp = input. read (data ))! =-1 ){
Output. write (data, 0, temp );
}
Input. close ();
Output. close ();
}
Public static void main (String [] args ){
String in = "C :\\ Users \ Administrator \ Desktop \ tmp.txt ";
String out = "C :\\ Users \ Administrator \ Desktop \ tmp_copy.txt ";
File src = new File (in );
File target = new File (out );
Try {
Long start = System. currentTimeMillis ();
CopyFile (src, target );
Long end = System. currentTimeMillis ();
System. out. println ("Copy Successfully! \ NAnd it costs us "+ (end-start) +" milliseconds .");
} Catch (IOException e ){
System. err. println ("ERROR: Something wrong while copying! ");
E. printStackTrace ();
}
}
}
Obviously, we can see the difference. Here we define a 1024-byte array. The size of this array is determined by ourselves. In fact, this is the combination with the first method.
Here we use the read () and write () methods, which are different from the previous ones, with parameters.
Read (byte B []) source code is as follows:
/**
* Reads some number of bytes from the input stream and stores them
* The buffer array <code> B </code>. The number of bytes actually read is
* Returned as an integer. This method blocks until input data is
* Available, end of file is detected, or an exception is thrown.
*
* <P> If the length of <code> B </code> is zero, then no bytes are read and
* <Code> 0 </code> is returned; otherwise, there is an attempt to read
* Least one byte. If no byte is available because the stream is at
* End of the file, the value <code>-1 </code> is returned; otherwise,
* Least one byte is read and stored into <code> B </code>.
*
* <P> The first byte read is stored into element <code> B [0] </code>,
* Next one into <code> B [1] </code>, and so on. The number of bytes read is,
* At most, equal to the length of <code> B </code>. Let <I> k </I> be
* Number of bytes actually read; these bytes will be stored in elements
* <Code> B [0] </code> through <code> B [</code> <I> k </I> <code>-1] </code>,
* Leaving elements <code> B [</code> <I> k </I> <code>] </code> through
* <Code> B [B. length-1] </code> unaffected.
*
* <P> The <code> read (B) </code> method for class <code> InputStream </code>
* Has the same effect as: <pre> <code> read (B, 0, B. length) </code> </pre>
*
* @ Param B the buffer into which the data is read.
* @ Return the total number of bytes read into the buffer, or
* <Code>-1 </code> if there is no more data because the end
* The stream has been reached.
* @ Exception IOException If the first byte cannot be read for any reason
* Other than the end of the file, if the input stream has been closed, or
* If some other I/O error occurs.
* @ Exception NullPointerException if <code> B </code> is <code> null </code>.
* @ See java. io. InputStream # read (byte [], int, int)
*/
Public int read (byte B []) throws IOException {
Return read (B, 0, B. length );
}
The source code has been clearly written, "@ param B the buffer into which the data is read. ", the parameter is to read the byte array in the memory. If we continue, we find that this method actually calls read (byte B [], int off, int len)
In fact, we still use the read () method. We just call some encapsulated methods.
For the write (byte B [], int off, int len) method, the source code is as follows:
/**
* Writes <code> len </code> bytes from the specified byte array
* Starting at offset <code> off </code> to this output stream.
* The general contract for <code> write (B, off, len) </code> is that
* Some of the bytes in the array <code> B </code> are written to
* Output stream in order; element <code> B [off] </code> is the first
* Byte written and <code> B [off + len-1] </code> is the last byte written
* By this operation.
* <P>
* The <code> write </code> method of <code> OutputStream </code> CILS
* The write method of one argument on each of the bytes to be
* Written out. Subclasses are encouraged to override this method and
* Provide a more efficient implementation.
* <P>
* If <code> B </code> is <code> null </code>,
* <Code> NullPointerException </code> is thrown.
* <P>
* If <code> off </code> is negative, or <code> len </code> is negative, or
* <Code> off + len </code> is greater than the length of the array
* <Code> B </code>, then an <tt> IndexOutOfBoundsException </tt> is thrown.
*
* @ Param B the data.
* @ Param off the start offset in the data.
* @ Param len the number of bytes to write.
* @ Exception IOException if an I/O error occurs. In particle,
* An <code> IOException </code> is thrown if the output
* Stream is closed.
*/
Public void write (byte B [], int off, int len) throws IOException {
If (B = null ){
Throw new NullPointerException ();
} Else if (off <0) | (off> B. length) | (len <0) |
(Off + len)> B. length) | (off + len) <0 )){
Throw new IndexOutOfBoundsException ();
} Else if (len = 0 ){
Return;
}
For (int I = 0; I <len; I ++ ){
Write (B [off + I]);
}
}
Similarly, this method also encapsulates the write (int B) method.
In addition, I added a small function that can test the time-consuming function. The principle is very simple. It is to use the currentTimeMillis () method. The source code is as follows:
/**
* Returns the current time in milliseconds. Note that
* While the unit of time of the return value is a millisecond,
* The granularity of the value depends on the underlying
* Operating system and may be larger. For example, example
* Operating systems measure time in units of tens
* Milliseconds.
*
* <P> See the description of the class <code> Date </code>
* A discussion of slight discrepancies that may arise
* "Computer time" and coordinated universal time (UTC ).
*
* @ Return the difference, measured in milliseconds,
* The current time and midnight, January 1, 1970 UTC.
* @ See java. util. Date
*/
Public static native long currentTimeMillis ();
We can see that the return value of this method is the interval from the current time to the month of January 1, 1970, in milliseconds.
By now, we have implemented the simple file copy function, which is actually a practical application of IO. You can view the source code in the learning process. Many parameters, returned values, and other details are described in detail. Using Eclipse for such a long time is the true love of java Programmers. The code prompt function is very powerful, so I am afraid that one day I can't write "Hello World" without Eclipse. ^_^. When you are studying IO, you can either watch videos or academic schools. The teacher will tell you how important IO is and how important it is to be learned, therefore, you may wish to write a few small functions in the learning process, so that you can better understand IO. This time I was just on the rise. It doesn't mean that this is the final implementation. You can combine what you learned and modify your code at will, but don't forget your purpose.
This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151440.htm