到目前为止,我有一个图像列表,我想根据从数据库获得的信息重命名它们。
图像列表:
IBImages = ["foo1", "foo2", "foo3"]
private static void buildTheme(ArrayList<String> IBImages) {
String bundlesPath = "/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",
"Icon-40@2x.png",
"Icon-40@3x.png",
"Icon-Small.png",
"Icon-Small@2x.png",
]
}
最佳答案
您不能同时将几个同名的文件放入目录中。您需要复制文件一次并重命名它,或者使用新名称创建空文件并将原始文件中的位复制到其中。第二种方法非常简单,使用 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
}
关于java - 将图像复制到新目录并重命名 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399083/