Read entire file in folder

Is there a way in Java where I can specify a directory in java and it reads the whole file one by one?

Otherwise, is there a way to make a regex file read in java? Therefore, if all the files in the folder all start with gh001_12312 gh002_12312, gh003_12911, gh004_22222, gh005_xxxxx, etc.

+3
source share
3 answers

The Java standard library provides a way to get an array of elements Filethat are in a directory through File # listFiles . Primarily:

File theDirectory = new File("/home/example");
File[] children = theDirectory.listFiles();

In addition, there is an overloaded method that allows you to specify a filter that you can use to trim items returned in the list.

File theDirectory = new File("/home/example");
File[] children = theDirectory.listFiles(new FileFilter(){
    public boolean accept(File file) {
        if (file.isFile()) {
           //Check other conditions
           return true;
        }
        return false;
    }
});

, String, Pattern Matcher. , , , File.listFiles(FilenameFilter), , .

+5

commons-io. , , ( , ). String.

Iterator<File> iterateFiles(File directory,
                                          String[] extensions,
                                          boolean recursive)
String readFileToString(File file)
                               throws IOException
+3

@Tim Bender :

, @Tim Bender ( ). .

File theDirectory = new File("/home/example");
File[] children = theDirectory.listFiles(new FileFilter(){
    public boolean accept(File file) {
        if (file.isFile()) {
           //Check other conditions
           return true;
        }
        return false;
    }
});

Now iterate over this array and use the java.nioAPI to read files at a time (without br.readLine())

public StringBuilder readReplaceFile(File f) throws Exception
{
    FileInputStream fis = new FileInputStream(f);
    FileChannel fc = fis.getChannel();

    int sz = (int)fc.size();
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);

    CharBuffer cb = decoder.decode(bb);

    StringBuilder outBuffer = new StringBuilder(cb);
    fc.close();
    return outBuffer;
}

Hope for this help

+1
source

Source: https://habr.com/ru/post/1794630/


All Articles