Java使用不带缓冲的字节流I/O实现任意文件拷贝
流程:
1.创建两个 f i l e file file文件,一个是 s o u r c e f i l e source\ file source file,一个是 t a r g e t f i l e target\ file target file。
2. s o u r c e f i l e source\ file source file用文件输入字节流对象, t a r g e t f i l e target\ file target file用文件输出字节流对象。
3. n e w new new 一个字节数组,然后用把 s o u r c e f i l e source\ file source file读入到里面,然后再将其写到 t a r g e t f i l e target\ file target file里面。
package Exp7;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Example7_4_1 {
static File file1,file2; //这里的文件要用静态的.
public static void main(String[] args) {
file1=new File("d:/Code/heykong.mp3"); //待拷贝的文件路径,这里的路径要存在
file2=new File("d:/Code/tmp.mp3"); //拷贝完之后的文件路径
try {
FileInputStream fis = new FileInputStream(file1); //创建文件输入流(字节流)对象
FileOutputStream fos = new FileOutputStream(file2);
/*FileInputStream fis = new FileInputStream("c:\\music\\notepad.exe");
FileOutputStream fos = new FileOutputStream("c:\\music\\notepad2.exe");
FileInputStream fis = new FileInputStream("c:\\music\\test.txt");
FileOutputStream fos = new FileOutputStream("c:\\music\\test2.txt");*/
System.out.println("正在拷贝...");
byte[] ba=new byte[fis.available()]; //定义字节数组,大小为文件长度
//byte[] ba=new byte[8]; //字节数组长度较小,导致拷贝文件不全
fis.read(ba); //一次性读取全部文件内容
fos.write(ba); //写入
System.out.println("拷贝完成。");
fis.close();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果target file
已经存在了就会覆盖掉原来的。
package Exp7;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFile {
public static void main(String[] args) {
File source_file = new File("d:/Code/heykong.mp3");
File target_file = new File("d:/Code/copy_file.mp3");
try{
FileInputStream fis = new FileInputStream(source_file);
FileOutputStream fos = new FileOutputStream(target_file);
byte []be = new byte[fis.available()];
System.out.println("正在拷贝.....");
fis.read(be);
fos.write(be);
System.out.println("拷贝完成!");
fis.close();
fos.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}