ตัวอย่างการคัดลอกไฟล์
ต่อไปนี้คือตัวอย่างโดยจะทำการคัดลอกไฟล์ที่ชื่อ "Afile.txt" ที่อยู่ใน "C:\\users\\nopphanan7" ไปเป็นไฟล์ที่ชื่อ "Bfile.txt".
package demo.file;
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 CopyFileExample {
/**
* @param args
*/
public static void main(String[] args) {
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File("C:\\users\\nopphanan7\\Afile.txt");
File bfile = new File("C:\\users\\nopphanan7\\Bfile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
ผลลัพธ์ที่ได้คือ
File is copied successful!
0 comments:
Post a Comment