Home > Article > Software Tutorial > Use Java code to read all txt documents in a folder, including those in subfolders
Create a new class, name it FileHandler, put the following code into it, and set basePath to the folder path you want to read. Read and write methods have been provided and you can call them as needed. ```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";
/**
* Find all files in the folder that match csv
*
* @param dir The folder object to be found
**/
public static void findFile(File dir) throws IOException{
File[] dirFiles = dir.listFiles();
for(File temp : dirFiles){
if(!temp.isFile()){
findFile(temp);
}
//Find the specified file
if(temp.isFile() & temp.getAbsolutePath().endsWith(".txt") ){
System.out.println(temp.isFile() " " temp.getAbsolutePath());
readFileContent(temp);
}
}
}
/**
* @param file The file object to be read
* @return Returns the contents of the file
**/
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 The file object to be written
* @param content The content of the file to be written
**/
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();
}
}
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 'Change c:\windows to the actual folder when using it
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,"Apple") > 0 Then
Cells(L, 1) = f1.Name
Cells(L, 2) = f1.Path
L = L 1
End If
End If
Next
End Sub
The above is the detailed content of Use Java code to read all txt documents in a folder, including those in subfolders. For more information, please follow other related articles on the PHP Chinese website!