开发者

Java Move File With Certain File Extension

开发者 https://www.devze.com 2023-02-27 20:58 出处:网络
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 t开发者_Python百科here need to be moved into another fo

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 t开发者_Python百科here 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


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
}


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.


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")
  }
});


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


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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消