Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a zip file in which there are around 2000 files (in Zip and PDF Format), i want to search the files which begin with '0' or '1' or '2' & copy these files to a new location.

What I have tried:

I tried the below code, but this code is only searching files beginning with '0' and also not copying these files to a new location.

import java.io.*;
import java.util.*;
import java.lang.*;

public class Main { 
   public static void main(String[] args) {
      File dir = new File("E:\\abc");
      FilenameFilter filter = new FilenameFilter() {
         public boolean accept (File dir, String name) { 
            return name.startsWith("0");
         } 
      }; 
      String[] children = dir.list(filter);
      if (children == null) {
         System.out.println("Either dir does not exist or is not a directory"); 
      } else { 
         for (int i = 0; i< children.length; i++) {
            String filename = children[i];
            System.out.println(filename);
         } 
      } 
   } 
}
Posted
Updated 27-Apr-20 3:11am

You need to Override the accept(), see: java - Use of FilenameFilter - Stack Overflow[^]

You can use Files.copy() to copy files, see: How to Copy a File with Java | Baeldung[^]
 
Share this answer
 
v2
Comments
Mubasshir Farooque 26-Apr-20 2:45am    
Could you please help me with the proper code, as I am not much familiar with it.
RickZeeland 26-Apr-20 5:00am    
Neither am I, as I'm not a Java but a C# programmer :)
Maybe a real Java developer will come to the rescue ...
You say you want to use files that start with "0" "1" or "2" but you only accept files that start with "0". The code is doing exactly what you told it to do.
public boolean accept (File dir, String name) { 
            return name.startsWith("0");
         }

You need to modify your accept code to handle all three cases
<pre>public boolean accept (File dir, String name) { 
            return name.startsWith("0") || name.startsWith("1") || name.startsWith("2");
         }


As for copying, try the java.nio.file.Files.copy function.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900