I need to read all ".txt" files from folder (user needs to select this folder).
Please advise how to do it?
Assuming you already have the directory, you can do something like this: File directory= new File("user submits directory"); for (File file : directory. listFiles()) { if (FileNameUtils. getExtension(file.
Core Java bootcamp program with Hands on practiceCreate a file object by passing the required file path as a parameter. Read the contents of each file using Scanner or any other reader. Append the read contents into a StringBuffer. Write the StringBuffer contents into the required output file.
In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false.
you can use filenamefilter
class it is pretty simple usage
public static void main(String[] args) throws IOException {
File f = new File("c:\\mydirectory");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
just create an filenamefilter
instance an override accept method how you want
Assuming you already have the directory, you can do something like this:
File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
if (FileNameUtils.getExtension(file.getName()).equals("txt"))
{
//dom something here.
}
}
The FileNameUtils.getExtension() can be found here.
Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With