将.txt中的名称映射到java中的文件夹

时间:2015-07-18 07:50:53

标签: java

我有一个名为附件的文件夹,其中包含5个.gif图像,我有一个att.txt,其中包含此.gif图像的名称,现在我需要使用att.txt中的名称重命名这些图像。 下面是我试过的代码。请帮助

public static void main(String[] args) throws java.lang.Exception {
    java.io.BufferedReader br = new java.io.BufferedReader(new FileReader("D:\\template_export\\template\\attachments"));
    String sCurrentLine="";
    while ((sCurrentLine = br.readLine()) != null) {
         sCurrentLine= sCurrentLine.replaceAll("txt", "gif");
         String[] s = sCurrentLine.split(",");
         for(int i=0;i<s.length;i++){
             new File("D:\\template_export\\template\\attachment_new"+s[i]).mkdirs();
             System.out.println("Folder Created");
         }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

public class Tst {

public static void main(String[] args) {
    File orgDirectory = new File("attachements");// replace this filename 
                                                 // with the path to the folder 
                                                 // that contains the original images

    String fileContent = "";
    try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachements.txt")))) {
        for (String line; (line = br.readLine()) != null;) {
            fileContent += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    String[] newLocations = fileContent.split(" ");
    File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getPath().endsWith(".gif");
        }
    });
    File destinationFolder = new File("processed");
    int max = Math.min(orgFiles.length, newLocations.length);
    for (int i = 0; i < max; i++) {
        String newLocation = newLocations[i];
        int lastIndex = newLocation.lastIndexOf("/");
        if (lastIndex == -1) {
            continue;
        }
        String newDirName = newLocation.substring(0, lastIndex);
        String newName = newLocation.substring(lastIndex);
        File newDir = new File(destinationFolder, newDirName);
        if (!newDir.exists()) {
            newDir.mkdir();
        }
        try {
            Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

它可能不会起作用,因为你的描述并不清楚,但我希望你明白这一点,并且你理解如何完成这项任务。重要的部分是:

File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getPath().endsWith(".gif");
        }
 });

创建一个File数组,其中包含所有&#34; gif&#34;源目录中的文件。

Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);

将原始图像移动到新目录,并将其名称设置为从&#34; attachements.txt&#34;中检索到的名称。文件。