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; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM