本帖最后由 Peach2014 于 2014-4-7 16:09 编辑
package study;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileStreamPicCopy {
public static void main(String[] args) {
//读一个字节写一个字节
long start1 = System.currentTimeMillis();
pictureCopy_1();
long end1 = System.currentTimeMillis();
System.out.println("字节读取复制完成,花费时间" + (end1-start1) + "毫秒");
//自定义缓冲器byte[1024]
long start2 = System.currentTimeMillis();
pictureCopy_2();
long end2 = System.currentTimeMillis();
System.out.println("自定义缓冲区复制完成,花费时间" + (end2-start2) + "毫秒");
//定义字符流缓冲区
long start3 = System.currentTimeMillis();
pictureCopy_3();
long end3 = System.currentTimeMillis();
System.out.println("定义字符流缓冲区复制完成,花费时间" + (end3-start3) + "毫秒");
}
//读一个字节写一个字节
public static void pictureCopy_1() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("toy.jpg");
fos = new FileOutputStream("toy1.jpg");
int ch;
while((ch=fis.read())!=-1) {
fos.write(ch);
}
} catch (Exception e) {
throw new RuntimeException("图片读取失败!");
} finally {
try {
if(fis!=null) {
fis.close();
}
} catch (IOException e) {
throw new RuntimeException("图片读取关闭失败!");
}
try {
if(fos!=null) {
fos.close();
}
} catch (IOException e) {
throw new RuntimeException("图片写入关闭失败!");
}
}
}
//自定义缓冲器byte[1024]
public static void pictureCopy_2() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("toy.jpg");
fos = new FileOutputStream("toy2.jpg");
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1)
{
fos.write(buf, 0, len);//这里修改后,应该就可以解决问题了,我按照你的程序运行,没有发现问题,我个人分析,问题是可能发生
//读取的和写入的内容不一致,这里对读取长度进行记录,保证了读写一致
}
// while((fis.read(buf))!=-1) {
// fos.write(buf);
// }
} catch (Exception e) {
throw new RuntimeException("图片读取失败!");
} finally {
try {
if(fis!=null) {
fis.close();
}
} catch (IOException e) {
throw new RuntimeException("图片读取关闭失败!");
}
try {
if(fos!=null) {
fos.close();
}
} catch (IOException e) {
throw new RuntimeException("图片写入关闭失败!");
}
}
}
//定义字符流缓冲区
public static void pictureCopy_3() {
BufferedInputStream bufis = null;
BufferedOutputStream bufos = null;
try {
bufis = new BufferedInputStream(new FileInputStream("toy.jpg"));
bufos = new BufferedOutputStream(new FileOutputStream("toy3.jpg"));
int by = 0;
while((by=bufis.read())!=-1) {
bufos.write(by);
}
} catch (Exception e) {
throw new RuntimeException("图片读取失败!");
} finally {
try {
if(bufis!=null) {
bufis.close();
}
} catch (IOException e) {
throw new RuntimeException("图片读取关闭失败!");
}
try {
if(bufos!=null) {
bufos.close();
}
} catch (IOException e) {
throw new RuntimeException("图片写入关闭失败!");
}
}
}
}
|