ITeye博客

IO About file copy

arlord · 2014-06-03 23:10 · 编程语言 · Markdown

package demo;

import java.io.*;

public class TestCopy{ public void testCopy()throws Exception{ FileInputStream fis = new FileInputStream("c:/爱是永恒.mp3"); int offset = 0; FileOutputStream fos = new FileOutputStream("d:/test.mp3"); while((offset = fis.read()) != -1){ fos.write(offset); } fis.close(); fos.close(); }

//使用缓存来提高效率
public void testCopy2()throws Exception{
	FileInputStream fis = new FileInputStream("c:/爱是永恒.mp3");
	//定义一个缓存用来装载读取到的文件
	byte[] temp = new byte[1024];
	int offset = 0;
	FileOutputStream fos = new FileOutputStream("d:/test2.mp3");
	//fis.read(temp) 把文件内容读取到temp数组,读到temp满为止或者没有内容
	//fis.read(temp)的返回值是实际读取进数组的字节个数
	while((offset = fis.read(temp)) != -1){
		//每次把一整个数组的数据写入文件,0表示从temp的第0个位置开始读取,
		//一共读取offset个写入到内容
		fos.write(temp,0,offset);
	}
	fis.close();
	fos.close();
}

public static void main(String[] args)throws Exception{
	TestCopy t = new TestCopy();
	t.testCopy2();
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。