java struts2复制文件到另一个目录下

来源:互联网 发布:edu是什么域名 编辑:程序博客网 时间:2024/06/06 15:03
这里主要是获取路径下的文件,通过过去此文件的文件名称,然后到目标目录下创建相同的文件名(当然可以自己自定义,我这里是为了项目需要)。再通过I/O流,将原文件写入到目标文件中去。


/**
* 复制广告里面的内容,到客户端的目录下面
* @param advPath(原文件位置)
* @throws IOException
*/
public void copyFile(String advPath) throws IOException{
int i=advPath.lastIndexOf("/");//获取路径最后一个“/”的位置
String s=advPath.substring(40,i+1).toLowerCase();//获取路径中位置40~i+1的字符串
String s1=advPath.substring(i+1);//获取 路径最后一个“/”后面的文件名称
String path=ServletActionContext.getServletContext().getRealPath("")+isexistdir(s);//获取根目录
// String savepath=isexistdir(s);
File flie= new File(path+s1);
if(!flie.exists()){
//判断此路径下的文件是否存在,不存在则重新创建
flie.createNewFile();
}
FileWriter fw = new FileWriter(flie);
PrintWriter pw = new PrintWriter(fw);
pw.println();
pw.flush();
fw.close();
int byteread=0;

InputStream in = new FileInputStream(advPath);//打开原文件
OutputStream out = new FileOutputStream(path+s1);//打开连接到目标文件的输出流
byte[] buffer = new byte[1024]; //一次读取1024字节。当byteread=-1时表示文件已经读完
while ((byteread = in.read(buffer)) != -1) {
//将读取的字节写入输出流
out.write(buffer, 0, byteread);
}
out.flush();
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}


}

这里的代码还是不够全面,不是很全面。我也有个一个问题,还想请大神们赐教!
String s=advPath.substring(40,i+1).toLowerCase();//获取路径中位置40~i+1的字符串
这个地方,假如 advPath="D:\alextao\elecartserver\WebContent/ADV/Picture/2013012514592153187.jpg";我想动态的获取“Picture”这个目录名称,而不是通过上面写死的了放在那里。
小弟,对于这里还没弄明白,还请各位大神赐教。
各位大神:小弟初来乍到,还请轻拍!!

原创粉丝点击