Java中有没有一种方法可以在Java中指定一个目录并逐个读取整个文件?
否则有没有办法在java中读取正则表达式文件?所以如果文件夹中的所有文件都以gh001_12312 gh002_12312、gh003_12911、gh004_22222、gh005_xxxxx等开头
标准 Java 库提供了一种通过File#listFilesFile
获取目录中元素数组的方法。基本上:
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;
}
});
如果您还想根据文件名进行一些过滤,请查看String、Pattern和Matcher。如果您知道只有文件或文件将遵循特定的命名约定,那么还有一个File.listFiles(FilenameFilter)
选项只提供一个表示文件名的字符串。
您可以使用commons-io中的以下方法的组合。第一种方法使您可以选择递归地遍历目录中与特定扩展名匹配的所有文件(还有另一个重载方法允许您提供自己的过滤器)。第二种方法将文件的全部内容作为 String 对象读取。
Iterator<File> iterateFiles(File directory,
String[] extensions,
boolean recursive)
String readFileToString(File file)
throws IOException
我在这里重用@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;
}
希望这有帮助