FileOutputStream的read()和write()方法,實現,abc.txt文件的拷貝新建IOUitl.java,代碼如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class IOUitl {
public static void copyfile(File src,File des)throws IOException{
if(!src.exists()){
throw new IllegalArgumentException(src+"原文件不存在");
}
if(!src.isFile()){
throw new IllegalArgumentException(src+"不是文件");
}
FileInputStream in = new FileInputStream(src);
//文件不存在直接創建,文件存在刪除後創建
FileOutputStream out = new FileOutputStream(des);
byte[] buf = new byte[8*1024];
int b;
//in.read(buf,0,buf.length)將讀的數據存在buf數組,從0開始到數組長度
while((b=in.read(buf,0,buf.length))!=-1){
out.write(buf, 0, b);
out.flush();
}
in.close();
}
}
再定義一個Test.java的類進行測試:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
public class Test2 {
public static void main(String[] args){
File src = new File("E:\\JavaIO\\abc.txt");
File des = new File("E:\\JavaIO\\abc1.txt");
try {
IOUitl.copyfile(src, des);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
運行結果,打開文件目錄,即可看到abc1.txt文件,裏面內容和abc.txt一樣,實現拷貝