java 移动文件并删除原文件
需求是这样的,先上传文件,因为只传文件没有办法生成一级目录文件夹,传过来参数又不好取,所以就先上传,然后后面提交的时候移动文件到新的目录:
public static String moveFile(String name, String path, String number) throws IOException { //移动文件夹 File fromPath = new File(path + File.separator + name);
//这个url不要new File,否则outStream的地方报错,拼出来的路径是:D:/resources/uploads/123/abc.png String url = path + File.separator + number + File.separator + name; FileChannel in = null; FileChannel out = null; FileInputStream inStream = null; FileOutputStream outStream = null; try { inStream = new FileInputStream(fromPath); File toPath = new File(path + File.separator + number); System.out.println("fileUrl: " + toPath); if (!toPath.exists()) { toPath.mkdirs(); } outStream = new FileOutputStream(url); in = inStream.getChannel(); out = outStream.getChannel(); IOUtils.copy(inStream, outStream); } catch (IOException e) { e.printStackTrace(); } finally { inStream.close(); in.close(); outStream.close(); out.close(); //删除原来文件,必须等流关闭后才能删除 fromPath.deleteOnExit(); }
//这是存入数库的路径 String imagePath = "/uploads/" + number + "/"+ name; return imagePath; }