【问题标题】:Copy image to new directory and rename - Java将图像复制到新目录并重命名 - Java
【发布时间】:2015-04-08 13:28:51
【问题描述】:

到目前为止,我有一个图像列表,我想根据从数据库中获得的信息重命名它们。

图片列表:

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",
    ]
}

【问题讨论】:

  • 我不知道你的问题是什么。你想知道如何在 java 中重命名文件吗?
  • 我正在尝试将文件从一个位置复制到另一个位置并重命名图像。
  • 是的,但有什么问题?你试过什么?为什么不工作?顺便说一句,看看java.nio.file.Files
  • 我什么都没试过。我对 Java 还是比较陌生,但我有其他编程经验。我正在尝试某人如何在文件夹中拍摄图像并复制 x 次,其中 x 是列表中的字符串数。所以我可能想拍一张名为 Facebook.png 的照片,将其复制到新文件夹 11 次并重命名 11 次(每次根据列表中的字符串名称重命名不同)。我想看看有人如何做到这一点。

标签: java json image copy rename


【解决方案1】:

您不能一次将几个同名文件放入目录中。您需要复制一次文件并重命名它,或者使用新名称创建空文件并将原始文件中的位复制到其中。第二种方法很容易使用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
}

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 2016-12-23
    • 1970-01-01
    • 2022-12-05
    • 2013-08-25
    • 1970-01-01
    • 2017-11-24
    • 2013-10-25
    • 2012-10-12
    相关资源
    最近更新 更多