Package Com.starain.io;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
public class Bytereadandwrite {
public static void Main (string[] args) throws IOException {
/* Normal binary read/write complete copy file method, low efficiency */
File filePathName1 = new file ("D:/1.txt");
File FilePathName2 = new file ("E:/1.txt");
try {
FileInputStream file1 = new FileInputStream (filePathName1);
FileOutputStream file2 = new FileOutputStream (filePathName2);
byte put[] = new BYTE[12];
int count1 = 0;
while (File1.read (put)!=-1) {
File2.write (Put);
count1++;
}
System.out.println ("read" +count1+ "Times");
File1.close ();
File2.close ();
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("error");
}
/*buffered method Read/write copy large file */
File FilePathName3 = new file ("E:/download/struts2_ value stack. wmv");
File FilePathName4 = new file ("F:\\struts2_ value stack. wmv");
try {
FileInputStream file3 = new FileInputStream (FILEPATHNAME3);
FileOutputStream file4 = new FileOutputStream (FILEPATHNAME4);
Bufferedinputstream bufferedFile1 = new Bufferedinputstream (file3,1000000);//hard drive in 1000, change buffer size to save time, optimize read and write purposes
Bufferedoutputstream bufferedFile2 = new Bufferedoutputstream (file4,1000000);
byte []put2 = new byte[100000];
int count2 = 0;
Long longTime1 = System.currenttimemillis ();
while (Bufferedfile1.read (PUT2)!=-1) {
Bufferedfile2.write (PUT2);
count2++;
}
Long longTime2 = System.currenttimemillis ();
System.out.println ("spents:" + (LONGTIME2-LONGTIME1) + "MS");
System.out.println ("with" +count2+ "Times");
/* Must develop good habits to prevent memory leaks
* First created and then closed
* After creating the first close
*/
Bufferedfile1.close ();
Bufferedfile2.close ();
File3.close ();
File4.close ();
} catch (FileNotFoundException e) {
System.out.println ("Error2");
}
}
}
Java Binary File replication