用java过滤脚本文件_Java 的 FileFilter文件过滤与readline读行操作实例代码
时间: 2024-02-27 10:52:16 浏览: 30
以下是用 Java 实现过滤脚本文件并读取行操作的示例代码:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
public class ScriptFileReader {
public static void main(String[] args) {
File dir = new File("path/to/directory");
File[] scriptFiles = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".js");
}
});
for (File scriptFile : scriptFiles) {
System.out.println("Reading file: " + scriptFile.getName());
try (BufferedReader br = new BufferedReader(new FileReader(scriptFile))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们首先创建了一个 `File` 对象来表示要读取的目录,然后使用 `listFiles()` 方法来获取该目录下所有的文件。接着,我们使用匿名内部类实现了一个 `FileFilter` 对象来过滤出扩展名为 `.js` 的脚本文件。最后,我们遍历所有过滤出的脚本文件,并使用 `BufferedReader` 和 `FileReader` 对象来读取每个文件的行。注意,我们使用了 try-with-resources 语句来自动关闭 `BufferedReader` 对象,这样可以避免手动关闭资源时遗漏关闭的情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)