java流复制文件_以java流的方式实现文件复制

简单的实现将文件复制到另一路径下,目前只支持单一文件的复制:

package com.jwnie.io;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.ParseException;

/**

*

* @author jwnie

*

*/

public class FileCopy {

public static void main(String[] args) throws FileNotFoundException,

IOException, ParseException {

copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\3\\2.txt");

copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\3\\2");

copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\jwnie");

copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\jwnie\\1.txt");

}

/**

*

* @param src

* 文件源

* @param dest

* 文件目的(可存在也可不存在,也可为目录或文件)

* @throws FileNotFoundException

* @throws IOException

* @throws ParseException

*/

public synchronized static void copyFile(String src, String dest)

throws FileNotFoundException, IOException, ParseException {

FileInputStream fis = null;

FileOutputStream fos = null;

File srcFile, destFile;

srcFile = new File(src);

// 利用字节类型的数组,一次性读取1Kb数据再进行传输,比对单个字节读写效率更高

byte[] buf = new byte[1024];

if (srcFile.exists()) {

if (srcFile.isFile()) {

try {

destFile = new File(dest);

if (!destFile.exists()) {// 文件目的路径不存在

if (!destFile.toString().contains(".")) {// 文件目的路径指向目录

destFile.mkdirs();

String str = destFile.getAbsolutePath() + "\\"

+ srcFile.getName();

fos = new FileOutputStream(str);

System.out.println("文件目的路径不存在,且指向目录:" + str);

} else if (destFile.toString().contains(".")) {// 文件目的路径指向文件

int a = destFile.toString().lastIndexOf("\\");

String s = destFile.toString().substring(0, a);

new File(s).mkdirs();

destFile.createNewFile();

fos = new FileOutputStream(dest);

System.out.println("文件目的路径不存在,且指向文件:"

+ destFile.getPath());

}

} else {// 文件目的路径存在

if (destFile.isDirectory()) {// 文件目的路径指向目录

String str = destFile.getAbsolutePath() + "\\"

+ srcFile.getName();

fos = new FileOutputStream(str);

System.out.println("文件目的路径存在,且指向目录:" + str);

} else {// 文件目的路径指向文件

fos = new FileOutputStream(dest);

System.out.println("文件目的路径存在,且指向文件:" + dest);

}

}

fis = new FileInputStream(src);

int i = fis.read(buf, 0, buf.length);

System.out.println("开始复制....");

while (i != -1) {

fos.write(buf, 0, i);

i = fis.read(buf, 0, buf.length);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (fis != null) {

fis.close();

}

if (fos != null) {

fos.close();

}

}

} else {

System.out.println("目前暂支持文件的复制!");

}

System.out.println("复制成功!");

} else {

System.out.println("找不到指定路径下的文件!");

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值