永发信息网

java怎么拷贝文件到工作目录下

答案:2  悬赏:70  手机版
解决时间 2021-03-09 09:08
  • 提问者网友:萌卜娃娃
  • 2021-03-09 02:12
想拷贝本地磁盘上的一个文件到工程WebContent的load文件夹(相对路径)下怎么拷贝?
File file=new File(ServletActionContext.getRequest().getContextPath()+"/load");//目的相对路径
if(!file.exits()){
file.mkdir();

}
save(“c:/image.png”,file.toString());

拷贝方法:

save(String str1,String str2){
FileInputStream fis=new FileInputStream(new File(str1));
FileOutputStream fos=new FileOutputStream(new File(str2));(走到这一步就报错了,提示找不到文件,是因为路径错了么)
}
最佳答案
  • 五星知识达人网友:话散在刀尖上
  • 2021-03-09 03:32
肯定是路径错了或者文件不存在。
全部回答
  • 1楼网友:胯下狙击手
  • 2021-03-09 03:56
public void copyfile(string oldpath, string newpath) { try { int bytesum = 0; int byteread = 0; file oldfile = new file(oldpath); if (oldfile.exists()) { //文件存在时 inputstream instream = new fileinputstream(oldpath); //读入原文件 fileoutputstream fs = new fileoutputstream(newpath); 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(); } } public void copyfolder(string oldpath, string newpath) { try { (new file(newpath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 file a=new file(oldpath); string[] file=a.list(); file temp=null; for (int i = 0; i < file.length; i++) { if(oldpath.endswith(file.separator)){ temp=new file(oldpath+file[i]); } else{ temp=new file(oldpath+file.separator+file[i]); } if(temp.isfile()){ fileinputstream input = new fileinputstream(temp); fileoutputstream output = new fileoutputstream(newpath + "/" + (temp.getname()).tostring()); byte[] b = new byte[1024 * 5]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if(temp.isdirectory()){//如果是子文件夹 copyfolder(oldpath+"/"+file[i],newpath+"/"+file[i]); } } } catch (exception e) { system.out.println("复制整个文件夹内容操作出错"); e.printstacktrace(); } }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯