读取文件夹中的整个文件

时间:2011-02-25 05:33:23

标签: java java-io

在Java中是否有一种方法可以在java中指定目录并逐个读取整个文件?

否则有没有办法在java中读取正则表达式文件?因此,如果文件夹中的所有文件都以gh001_12312 gh002_12312,gh003_12911,gh004_22222,gh005_xxxxx等开头

3 个答案:

答案 0 :(得分:5)

标准Java库提供了一种通过File#listFiles获取目录中File元素数组的方法。 基本上是:

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

此外,还有一个重载方法允许指定过滤器,该过滤器可用于修剪列表中返回的元素。

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

如果您想根据文件名进行一些过滤,请查看StringPatternMatcher。如果您知道只有文件或文件将遵循某个命名约定,那么还有一个File.listFiles(FilenameFilter)选项,它们只提供表示文件名的字符串。

答案 1 :(得分:3)

您可以使用commons-io中以下方法的组合。第一种方法为您提供了迭代遍历目录中所有文件的选项,这些文件与特定扩展名匹配(有另一种重载方法允许您提供自己的过滤器)。第二种方法将文件的全部内容作为String对象读取。

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

答案 2 :(得分:1)

我在这里重用@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;
    }
});

现在迭代这个数组并使用java.nio API一次性读取文件(不含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;
}

希望这个帮助

相关问题