2015-02-08 76 views
0

到目前爲止,我有一張圖像列表,我想根據從數據庫獲取的信息重命名它們。將圖像複製到新目錄並重命名 - Java

圖像列表:

IBImages = ["foo1", "foo2", "foo3"] 

private static void buildTheme(ArrayList<String> IBImages) { 
    String bundlesPath = "https://stackoverflow.com/a/long/path/with/dest/here"; 

    for (int image = 0; image < IBImages.size(); image++) { 
     String folder = bundlesPath + "/" + image; 
     File destFolder = new File(folder); 
     // Create a new folder with the image name if it doesn't already exist 
     if (!destFolder.exists()) { 
      destFolder.mkdirs(); 
      // Copy image here and rename based on a list returned from a database. 
     } 
    } 
} 

你從數據庫中獲取的JSON可能是這個樣子。我要重命名的一個形象,我要所有的名字在icon_names名單

{ 
    "icon_name": [ 
      "Icon-40.png", 
      "[email protected]", 
      "[email protected]", 
      "Icon-Small.png", 
      "[email protected]", 
    ] 
} 
+0

我找不出你的問題是什麼。你想知道如何重命名在Java文件? – isnot2bad 2015-02-08 20:59:40

+0

我試圖將文件從一個位置複製到另一個位置並重命名圖像。 – tbcrawford 2015-02-08 21:03:37

+2

是的,但是有什麼問題?你有什麼嘗試?爲什麼不工作?順便說一句,看看['java.nio.file.Files'](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html)。 – isnot2bad 2015-02-08 21:07:33

回答

2

你不能與同名目錄幾個文件一次。您需要複製文件一次並重新命名,或者使用新名稱創建空文件並將原始文件中的位複製到文件中。第二種方法對於Files類和其copy(source, target, copyOptions...)方法是相當容易的。

下面是一個簡單的例子,將位於images/source/image.jpg中的一個文件複製到image/target目錄中的新文件,同時給它們新的名稱。

String[] newNames = { "foo.jpg", "bar.jpg", "baz.jpg" }; 

Path source = Paths.get("images/source/image.jpg"); //original file 
Path targetDir = Paths.get("images/target"); 

Files.createDirectories(targetDir);//in case target directory didn't exist 

for (String name : newNames) { 
    Path target = targetDir.resolve(name);// create new path ending with `name` content 
    System.out.println("copying into " + target); 
    Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); 
    // I decided to replace already existing files with same name 
}