本帖最后由 chen20134 于 2014-4-8 15:43 编辑
- import java.io.*;
- class CopyPic
- {
- public static void main(String[] args)
- {
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try
- {
- fis = new FileInputStream("1.jpg");
- fos = new FileOutputStream("2.jpg");
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=fis.read(buf))!=-1) //这里把read()改为read(buf)
- {
- fos.write(buf,0,len);
- }
- }
- catch (IOException e)
- {
- throw new RuntimeException("复制文件失败");
- }
- finally
- {
- try
- {
- if(fos!=null)
- fos.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("读取关闭失败");
- }
- try
- {
- if(fis!=null)
- fis.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("写入关闭失败");
- }
- }
- }
- }
复制代码
FileInputStream 中有三个读入的方法:
int read() 从此输入流中读取一个数据字节。
int read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
int read(byte[] b, int off, int len) 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
你的原程序使用的是read()方法,返回的是下一个数据的字节数,所以在write的时候写入的数据也不是存入buf的数据。
加上buf后调用的方法会一次读取1024字节的数据存在buf中。
你也可以参考FileInputStream 中的三个读入的方法进行修改
|