---
title: "IO  About file copy"
author: "arlord"
date: "2014-06-03T23:10:23Z"
tags: []
categories: ["编程语言"]
slug: "io-about-file-copy"
draft: false
lastmod: "2014-06-03T23:10:23Z"
id: 2075652
url: "https://arlord.iteye.com/blog/2075652"
---

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();
	}
}