0

I am trying to select all .txt files in known directory. For example I know the path : C:/../Desktop/ and now I want to take all .txt files which are on Desktop.

So which regularExpression should I use and how can i search it ? I dont know very much knowlegde about java. If you help me i will very happy.

String regularExpression = ?

String path = "C:/../Desktop/";
Pattern pattern = Pattern.compile(regularExpression);
boolean isMatched = Pattern.matches(regularExpression,path);
Dale
  • 1,903
  • 1
  • 16
  • 24
Batuhan B
  • 1,835
  • 4
  • 29
  • 39
  • If you want *work* with the files, use the tools provided in the package `java.nio`. Don't reinvent the wheel Oracle already build for you. –  Oct 18 '13 at 10:19
  • possible duplicate of [Listing files in a directory matching a pattern in Java](http://stackoverflow.com/questions/2102952/listing-files-in-a-directory-matching-a-pattern-in-java) – Joe Jun 01 '14 at 08:08

4 Answers4

5

Use Files.newDirectoryStream:

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class App {

    public static void main(String[] args) throws Exception {
        Path dir = Paths.get("/tmp", "subdir", "subsubdir");
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.txt")) {
            for (Path path : stream) {
                System.out.println(path.getFileName());
            }
        }    
    }
}

On Windows, build the Path of the directory as described for Paths.get. This method accepts one or more parameters which together build up a path. In my example, the parameters /tmp, subdir, and subsubdir result in /tmp/subdir/subsubdir. On Windows, you would probably build the path from segments like C: and Desktop.

  • Could you please explain the Paths.get() parameters: My path is like: C:/Documents and Settings/username/Desktop/ so what should i write in the Paths.get() ?? – Batuhan B Oct 18 '13 at 10:21
4

Here is the answer:

String regularExpression = ".*\.txt";
Dale
  • 1,903
  • 1
  • 16
  • 24
0

"path".endsWith(".txt") will be faster

popfalushi
  • 1,332
  • 9
  • 15
0

Try this to process txt files, this will take all files inside the root folder and inner folder as well.

    public static void main(String[] arg"s) throws Exception {
     File dir = new File("YOUR_ROOT_FILE_PATH");
                    File[] dirs = dir.listFiles();
                    parseFiles(dirs);
}

        public static void parseFiles(File[] files) throws Exception {
                for (File file : files) {
                    if (file.isDirectory()) {
                        parseFiles(file.listFiles());
                    } else {
                        if(file.getAbsolutePath().endsWith(".txt"){
        //do ur stuff here or call a function and pass this file as argument
                        }
                    }
                }
Rijo Joseph
  • 1,375
  • 3
  • 17
  • 33