Everyone in Java development will encounter file copy files, it is well known that the need for file input and output stream implementation.
What the hell to do that, say not much, directly on the code:
One, copy the file using the byte stream
public class Filebytecopy {
public static void Main (string[] args) {
Filebytecopy f= new Filebytecopy ();
try {
F.copy ("D:/file/1.txt", "d:/copyfile/1.txt");
} catch (Exception e) {
E.printstacktrace ();
}
}
public void copy (String f1,string F2) throws exception{
FileInputStream fis = new FileInputStream (F1); First build the object of the input stream, specifying the file path to be read
FileOutputStream fos = new FileOutputStream (f2,false); The object that builds the file output stream, where the file is to be copied, followed by true to not empty the current file content on each write
Method one, single-byte replication
int value = Fis.read (); ///One byte read the contents of a file
while (Value!=-1) {
Fos.write (value);
Fos.flush ();
Value = Fis.read ();
// }
Method Two is passed in a byte array (one-size-custom array is passed at a time)
byte [] bytes = new byte[1024];
int Len=fis.read (bytes); To deposit the bytes read into the byte array at this time Len is the size of the file, note that it is not necessarily 1024. The Len value of the corresponding source file is 95 bytes in the
while (Len!=-1) {
Fos.write (bytes); With this method, if the source file size is not 1024, the copied file will also be 1024. Because the minimum of one read is 1024, see in detail.
Before copying
After copying
Fos.write (bytes, 0, Len); Writing characters from offset 0 to Len (95) guarantees that the source file and the copied file are the same size.
Fos.flush ();
Len=fis.read (bytes);
}
Close the stream when read is complete
Fis.close ();
Fos.close ();
}
}
Second, copy files using character stream (same as Byte stream)
public class Filecharcopy {
public static void Main (string[] args) {
Filecharcopy f = new filecharcopy ();
try {
F.copy ("D:/file/1.txt", "d:/copyfile/1.txt");
} catch (Exception e) {
E.printstacktrace ();
}
}
public void copy (String f1,string F2) throws exception{
FileReader FR = new FileReader (F1);
FileWriter FW =new FileWriter (F2,false);
int Value=fr.read ();
while (Value!=-1) {
Fw.write (value);
Fw.flush ();
Value=fr.read ();
//}
char [] chars = new char[1024];
int len =fr.read (chars);
while (Len!=-1) {
Fw.write (chars, 0, Len);
Fw.flush ();
Len =fr.read (chars);
}
Fr.close ();
Fw.close ();
}
Java implements file replication using byte stream and character flow