- import java.io.*;
- public class CopyPicture {
-
- public static void main(String[] args) {
- copyPic();
- }
-
- public static void copyPic() {
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream("psb.jpg");
- BufferedInputStream bi = new BufferedInputStream(fis);
- fos = new FileOutputStream("psb1.jpg");
- BufferedOutputStream bo = new BufferedOutputStream(fos);
- byte[] b = new byte[1024];
- int leng;
- while((leng = bi.read(b, 0, b.length)) != -1) {
- bo.write(b, 0, leng);
- bo.flush();
- }
- /* byte[] buf = new byte[1024];
- int len = 0;
- while ((len = fis.read(buf)) != -1) {
- fos.write(buf, 0, len);
- fos.flush();// 不可以忘记!!!
- }*/
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fos != null) {
- try {
- fos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (fis != null) {
- try {
- fis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码 在此我认为我有必要说明一下 FileInputStream 和 BufferedInputStream中的read方法的区别
FileInputStream 是从硬盘上一个字节,一个字节的读取,速度相当的慢,但是如果在外面套一层BufferedInputStream,因为BufferedInputStream内部有一个缓冲区,首先
读取一次数据,将缓冲区填满,之后直接从缓冲区中读取数据,这样cpu访问硬盘的次数下降了好多,效率就提高了许多倍FileOutputStream和BufferedOutputStream是同样的道理 |