首页  >  文章  >  软件教程  >  使用Java代码读取文件夹中的所有txt文档,包括子文件夹中的txt文档

使用Java代码读取文件夹中的所有txt文档,包括子文件夹中的txt文档

王林
王林转载
2024-01-15 20:21:38785浏览

代码! java如何读取文件夹中所有txt文档包含子文件夹中的txt文

代码! java如何读取文件夹中所有txt文档包含子文件夹中的txt文

新建一个类,命名为FileHandler,将下面的代码放入其中,注意设置basePath为你要读取的文件夹路径。已经提供了读取和写入的方法,你可以根据需要调用。 ```java import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FileHandler { private String basePath; public FileHandler(String basePath) { this.basePath = basePath; } public String readFile(String fileName) throws IOException { String filePath = basePath + File.separator + fileName; byte[] bytes = Files.readAllBytes(Paths.get(filePath)); return new String(bytes); } public void writeFile(String fileName, String

static String basePath="/home/csvDir";

/**

* 查找文件夹下所有符合csv的文件

*

* @param dir 要查找的文件夹对象

**/

public static void findFile(File dir) throws IOException{

File[] dirFiles = dir.listFiles();

for(File temp : dirFiles){

if(!temp.isFile()){

findFile(temp);

}

//查找指定的文件

if(temp.isFile() & temp.getAbsolutePath().endsWith(".txt") ){

System.out.println(temp.isFile() + " " + temp.getAbsolutePath());

readFileContent(temp);

}

}

}

/**

* @param file 要读取的文件对象

* @return 返回文件的内容

**/

public static String readFileContent(File file) throws IOException{

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

StringBuffer sb = new StringBuffer();

while(br.ready()){

sb.append(br.readLine());

}

System.out.println(sb.toString());

return sb.toString();

}

/**

* @param file 要写入的文件对象

* @param content 要写入的文件内容

**/

public static void writeFileContent(File file,String content) throws IOException{

FileWriter fw = new FileWriter(file);

fw.write(content);

fw.flush();

fw.close();

}

public static void main(String[] args) {

try {

findFile(new File(basePath));

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

高分代码!用vba如何检索一个文件夹里所有txt文件中包含

Sub t()

Dim fso, f, f1, fc, s, r

Const ForReading = 1, ForWriting = 2

Set fso = CreateObject("Scripting.FileSystemObject")

'Set fc = fso.GetFile(WScript.ScriptFullName).ParentFolder.Files

Set fc = fso.GetFolder("c:windows").Files '使用时把c:windows改成实际的文件夹

L = 1

For Each f1 In fc

EXTName = UCase(fso.GetExtensionName(f1.Name))

If EXTName = "TXT" Then

Set fs = fso.OpenTextFile(f1, ForReading)

fb = fs.ReadAll

If InStr(1, fb, "苹果") > 0 Then

Cells(L, 1) = f1.Name

Cells(L, 2) = f1.Path

L = L + 1

End If

End If

Next

End Sub

以上是使用Java代码读取文件夹中的所有txt文档,包括子文件夹中的txt文档的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:docexcel.net。如有侵权,请联系admin@php.cn删除