Java Move File With Certain File Extension

南笙酒味 提交于 2019-12-23 03:15:18

问题


Hi i'm working on a simple program and for the set up of the program i need the program to check a directory for zip files and any zip files in there need to be moved into another folder.

Lets say i have folder1 and it contains 6 zip files and then i have another folder called folder2 that i need all the zips and only the zips in folder1 moved to folder2

Thank you for any help one this problem.

Btw i'm a noob so any code samples would be greatly appreciated


回答1:


For each file in folder1, use String#endsWith() to see if the file name ends with ".zip". If it does, move it to folder2. FilenameFilter provides a nice way to do this (though it's not strictly necessary).

It would look something like this (not tested):

File f1 = new File("/path/to/folder1");
File f2 = new File("/path/to/folder2");

FilenameFilter filter = new FilenameFilter()
{
    @Override public boolean accept(File dir, String name)
    {
        return name.endsWith(".zip");
    }
};

for (File f : f1.listFiles(filter))
{
    // TODO move to folder2
}



回答2:


The pattern of matching "*.zip" in a filesystem is called "file globbing." You can easily select all of these files with a ".zip" file glob using this documentation: Finding Files. java.nio.file.PathMatcher is what you want. Alternatively, you can list directories as normal and use the name of the file and the ".endsWith()" method of String which will do something similar.




回答3:


Use a FilenameFilter

String pathToDir = "/some/directory/path";
File myDir = new File(pathToDir);
File[] zipFiles = myDir.listFiles(new FilenameFilter() {

  public boolean accept(File dir, String name) {
    return name.endsWith(".zip")
  }
});



回答4:


List all file in baseDir, if it ends with '.zip' moves it to destDir

    // baseDir = folder1
    // destDir = folder2

    File[] files = baseDir.listFiles();
    for (int i=0; i<files.length; i++){
        if (files[i].endsWith(".zip")){
            files[i].renameTo(new File(destDir, files[i].getName()));
        }
    }

API of renameTo




回答5:


My solution:

import java.io.*;
import javax.swing.*;
public class MovingFile
{
    public static void copyStreamToFile() throws IOException
    {
        FileOutputStream foutOutput = null;
        String oldDir =  "F:/CAF_UPLOAD_04052011.TXT.zip";
        System.out.println(oldDir);
        String newDir = "F:/New/CAF_UPLOAD_04052011.TXT.zip.zip"; // name the file in destination

        File f = new File(oldDir);              
        f.renameTo(new File(newDir));
    }
    public static void main(String[] args) throws IOException
    {
        copyStreamToFile();
    }
}


来源:https://stackoverflow.com/questions/5758268/java-move-file-with-certain-file-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!