您的位置 首页 java

第44期Java面试题:java如何复制文件

public class FileCopy {

/**

* 实现思路

* 1、构建源文件与目标文件

* 2、源文件创建输入流,目标文件创建输出流

* 3、创建字节数组

* 4、使用循环,源文件读取一部分内容,目标文件写入一部分内容,直到写完所有内容

* 5、关闭源文件输入流,目标文件输出流

* @param args

*/

public static void main(String[] args) {

//构建源文件

File file = new File(“E:” + File.separator + “helloworld.txt”);

//构建目标文件

File fileCopy = new File(“D:” + File.separator + “helloworld.txt”);

InputStream in = null;

OutputStream out = null;

try{

//目标文件不存在就创建

if(!(fileCopy. exists ())) {

fileCopy.createNewFile();

}

//源文件创建输入流

in = new FileInputStream(file);

//目标文件创建输出流

out = new FileOutputStream(fileCopy, true);

//创建字节数组

byte [] temp = new byte[1024];

int length = 0;

//源文件读取一部分内容

while((length = in.read(temp)) != -1) {

//目标文件写入一部分内容

out.write(temp, 0, length);

}

}catch(IOException e) {

e.printStackTrace();

}finally {

try {

in. close (); //关闭源文件输入流

out.close(); //关闭目标文件输出流

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

文章来源:智云一二三科技

文章标题:第44期Java面试题:java如何复制文件

文章地址:https://www.zhihuclub.com/174432.shtml

关于作者: 智云科技

热门文章

网站地图