【问题标题】:How do I move files to different directories based upon filename?如何根据文件名将文件移动到不同的目录?
【发布时间】:2013-12-03 05:37:13
【问题描述】:

好的,我已经创建了一个程序,它将根据创建日期重命名目录中的文件。我现在需要能够根据创建日期将这些文件移动到不同的目录中 - 20131202-1.jpg 将进入一个名为 20131202 的文件夹,一个名为 20131203-2.jpg 的文件将进入一个名为 20131203、20131130-1 的文件夹。 jpg 将进入一个名为 20131130 的文件夹 - 如果需要,创建目录等。有没有简单的方法可以做到这一点?这是我用于重命名的代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class FileRenameAndMove extends JFrame implements ActionListener {
    private JTextField filePath;
    private JTextField outputFile;
    private JButton input;
    private JButton output;
    private JButton rename;
    JFileChooser chooser ;
    File input_Folder = null;
    File output_Folder = null;

    public ExtraCredit(){
        filePath = new JTextField();
        outputFile = new JTextField();
        chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        input = new JButton("select input Folder");
        output = new JButton("select output Folder");
        rename = new JButton("rename File");
        setTitle("File Mover");
        setLayout(null);
        setVisible(true);
        setSize(500,200);

        filePath.setBounds(10,10,250,30);
        outputFile.setBounds(10,50,250,30);
        input.setBounds(280,10,150,30);
        output.setBounds(280,50,150,30);
        rename.setBounds(280, 90,150,30);

        add(filePath);
        add(outputFile);
        add(input);
        add(output);
        add(rename);

        input.addActionListener(this);
        output.addActionListener(this);
        rename.addActionListener(this);

    public static void main(String[] args) {
        new ExtraCredit();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==input){
              int option = chooser.showOpenDialog(this);
              if (option == JFileChooser.APPROVE_OPTION) {
                  input_Folder=chooser.getSelectedFile();
                  filePath.setText(input_Folder.getAbsolutePath());
              }
        }
        else if(e.getSource()==output){
              int option = chooser.showOpenDialog(this);
              if (option == JFileChooser.APPROVE_OPTION) {
                  output_Folder=chooser.getSelectedFile();
                  outputFile.setText(output_Folder.getAbsolutePath());
              }
        }
        else if(e.getSource()==rename){
              if(input_Folder==null||output_Folder==null){
                  JOptionPane.showMessageDialog(this,
                            "Please select the source and target folder",
                            "File error",
                            JOptionPane.ERROR_MESSAGE);
              }
              else{
                  if(input_Folder.exists()){
                      SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMdd");
                      File[] fileList = input_Folder.listFiles();

                      for(int i=0;i<fileList.length;i++){
                          new File(output_Folder.getAbsolutePath()+"/"+dateFormat.format(fileList[i].lastModified())).mkdir();
                          fileList[i].renameTo(new File(output_Folder.getAbsolutePath()+"/"+dateFormat.format(fileList[i].lastModified())+"/"+fileList[i].getName()));
                      }
                      JOptionPane.showMessageDialog(this,
                                "Files renamed successfully!!",
                                "Information",
                                JOptionPane.INFORMATION_MESSAGE);
                  }
                  else
                      JOptionPane.showMessageDialog(this,
                                "Source folder doesn't exists",
                                "File error",
                                JOptionPane.ERROR_MESSAGE);
              }
        }

    }

}

如果您能提供如何进行复制的示例,我将不胜感激。

【问题讨论】:

    标签: java


    【解决方案1】:

    我写了一个方法来做到这一点。它将首先获取当前目录并收集其中所有文件+文件夹的列表(非递归)。然后,它将遍历内容并确保它是一个带有“-”的文件,在这种情况下,它将创建文件夹并移动文件。

    import java.io.*;
    
    public class tmp {
        public static void main(String[] args) throws IOException {
            File folder = new File(System.getProperty("user.dir"));
            File[] files = folder.listFiles();
    
            for(int i = 0; i < files.length; i++) {
                if(files[i].isFile()) {
                    String name = files[i].getName();
                    if(name.indexOf("-") != -1) {
                        System.out.println(name);
                        name = name.substring(0, name.indexOf("-"));
                        new File(System.getProperty("user.dir") + "/" + name + "/").mkdirs();
                        files[i].renameTo(new File(System.getProperty("user.dir") + "/" + name + "/" + files[i].getName()));
                    }
                }
            }
    
        }
    }
    

    【讨论】:

    • 正斜杠适用于所有 Java 例程中的窗口。根本不需要使用 File.separator。
    • @AgilePro 谢谢你,我不太确定,从来没有为 Windows 机器编写过代码。
    【解决方案2】:
    1. 尝试使用mkdirs() 而不是mkidr() 创建目录,因为:mkdirs() 创建以此抽象路径名命名的目录,包括所有必要但不存在的父目录。

    2. file1.renameTo(file2) 无法将文件从一个目录移动到另一个目录。文档说:

    此方法的行为的许多方面都与生俱来 平台相关:重命名操作可能无法移动 文件从一个文件系统到另一个文件系统,它可能不是原子的,它 如果具有目标抽象路径名的文件可能不会成功 已经存在。 应始终检查返回值以确保 表示重命名操作成功。

    因此,首先使用流复制器(读取器和或写入器)方法将目标文件复制到目标目录,然后使用delete() 函数删除目标文件。或者您可以使用 JAVA NIO 支持来提高性能:

          public static void copyFile(File sourceFile, File destFile) throws IOException {
           if(!destFile.exists()) {
                destFile.createNewFile();
            }
    
            try( FileChannel source = new FileInputStream(sourceFile).getChannel();
               FileChannel destination = new FileOutputStream(destFile).getChannel()
               ) {
                 destination.transferFrom(source, 0, source.size());
                }
    
        }
    

    【讨论】:

    • 非常感谢。我现在将尝试按月份重命名文件夹,例如 Oct2013,而不是 20131011-1.jpg。祝我好运。 :)
    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    相关资源
    最近更新 更多