I want to write a short application . It must browse the files to seek the folders. If it find a folder, it write on console the name of folder and to into the folder. Next write to console name of txt files included in folder.
My code :
import java.io.File;
public class test {
public static void search(File f) {
File[] tab = f.listFiles();
for (File file1 : tab) {
if (file1.isDirectory()) {
search(file1);
} else {
if (Txt(file1)) {
System.out.println("+ " + file1);
}
}
}
}
public static boolean Txt(File f) {
return f.getName().substring(f.getName().length() - 4).equals(".txt");
}
public static void main(String[] args) {
try {
File f = new File("/home/mati/Pulpit");
search(f);
} catch (Exception e) {
}
}
}
Result of code :
+ New Folder
- aaa.txt
- abc.txt
- abf.txt
+ New Folder2
- abgh.txt
My program write only txt files , and i dont know how fix it …
Two things: first, to display the folder names, you will need to add a System.out in the branch of the code with the “if (file1.isDirectory())” conditional. You have a System.out in the “else” portion already, which is why the file names are displaying.
Secondly, though, this will probably not work the way you want it to if you have folders inside of folders. All folders will display with one level of indentation, and all of the files will display with the other. But you won’t be able to see which folders are nested in the others.