java后台copy文件的一个写法

/**

* 将上传的文件由本地硬盘考到本项目的服务部署的位置

*

* @param preparePath

*            String 原文件路径 如:c:/fqf.txt

* @param newPath

*            String 复制后路径 如:f:/fqf.txt

* @return boolean

*/

public static void copyFile(String storeFileName, String preparePath) {

try {

int bytesum = 0;

int byteread = 0;

// 获取系统根目录

String rootPath = (new File("")).getAbsolutePath();

rootPath = rootPath.substring(0, rootPath.lastIndexOf("\\"));

File file1 = new File(rootPath + "/apache-tomcat/webapps/mobileoa/res");

if (!file1.exists()) {

file1.mkdir();

}

File file2 = new File(rootPath + "/apache-tomcat/webapps/mobileoa/res/data");

if (!file2.exists()) {

file2.mkdir();

}

File oldfile = new File(rootPath + "/apache-tomcat/webapps/mobileoa/res/data/kmAttachment");

if (!oldfile.exists()) {

oldfile.mkdir();

}

// if (oldfile.exists()) { //文件存在时

InputStream inStream = new FileInputStream(preparePath); // 读入原文件

System.out.println("读入文件:" + preparePath);

FileOutputStream fs = new FileOutputStream(rootPath + "/apache-tomcat/webapps/mobileoa/res/data/kmAttachment/" + storeFileName);

System.out.println("最终目标文件:" + rootPath + "/apache-tomcat/webapps/mobileoa/res/data/kmAttachment/" + storeFileName);

System.out.println(fs);

byte[] buffer = new byte[1444];

// int length;

while ((byteread = inStream.read(buffer)) != -1) {

bytesum += byteread; // 字节数 文件大小

System.out.println(bytesum);

fs.write(buffer, 0, byteread);

}

inStream.close();

// }

} catch (Exception e) {

System.out.println("复制单个文件操作出错");

e.printStackTrace();

}

}

你可能感兴趣的:(java后台copy文件的一个写法)