2015-02-08 77 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 
}