您的位置:首页 > 编程语言 > Java开发

java文件,图片的复制

2013-11-17 01:21 267 查看
用java的IO,可以对数据的各种操作,对于文件复制的一般思路是:

1.先建立目标文件A,即要复制的文件,然后建立复制后的文件名B

2..建立管道,连接源文件

3.数据的操作,采用循环的方式,从目标文件A读取数据到缓冲区然后将缓冲区的内容输出到文件B中

4.关闭文件

注意的是:

1.正常必须关闭文件(对于java7新采用了另一种独特方式,不必手动关闭)

2.在关闭文件时,先开的后关

3..对关闭的文件的异常操作 操作,可以采用以下例子的方式

用这个代码可以复制一般的文本,同时还可以复制图片

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

public class IOExercise3 {

public void copy(File srcFile, File targetFile)

{

/**

* srcFile为源文件,targetFile目标文件

*

* */

if(srcFile == null || targetFile == null)

{

System.out.println("文件打开失败");

return;

}

// 2.建立管道

OutputStream os = null;

InputStream is = null;

try {

os = new FileOutputStream(targetFile);

is = new FileInputStream(srcFile);

// 3.读取操作

// 先建立缓冲区,为1024个字节大小

byte [] b = new byte[1024];

int len = 0;

// 采用循环的方式读取文件的内容

while ((len= is.read(b)) != -1)

{

String data = new String (b, 0, b.length);

// System.out.println(data);

os.write(b);

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

// 一般先开的后关

try {

if(os != null)

os.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

try {

if(is != null)

is.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

public static void main(String [] args) throws IOException

{

File srcFile = new File("1.jpg");

File targetFile = new File("2.jpg");

new IOExercise3().copy(srcFile, targetFile);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: