File copy
In this chapter you will learn:
Use FileInputStream and FileOutputStream to copy a file
The following code use FileInputStream
and FileOutputStream
to copy a file.
It creates FileInputStream
from source file path
and creates FileOutputStream
for target file path.
Then it reads the source file byte
by byte
and writes to
the target file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/* j a v a 2 s .c o m*/
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream fin = null;
FileOutputStream fout = null;
File file = new File("C:/myfile1.txt");
fin = new FileInputStream(file);
fout = new FileOutputStream("C:/myfile2.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fin.read(buffer)) > 0) {
fout.write(buffer, 0, bytesRead);
}
fin.close();
fout.close();
}
}
The close() methods for both input and output streams are important. Remember to close them.
Next chapter...
What you will learn in the next chapter:
- Stream vs Reader and writer
- Get to know InputStream
- Get to know OutputStream
- Get to know Reader
- Get to know Writer
Home » Java Tutorial » I/O