Zed Zed - 3 months ago 8
Java Question

Writing to all txt files in directory and in the sub dirs

so I'm not a coding student or anything. I'm doing this for a personal project that I wanted to do. I've spent hours with multiple codes trying to figure this out and I'm pretty close. I want to pick a directory, and then write to all the text files in every single sub directory it has. I don't want to list out every single subdirectory, as they will be increasing in size over time and I don't want to have to edit this code.

When this runs, it will write to ever text file in the directory, but the sub directories say java.nio.file.AccessDeniedException

The files do exist, and it's on my desktop so access shouldn't be an issue

I'm completely stumped as to what do do now. If I was actually a programming student I bet this wouldn't be an issue, but I'm not so yeah. Any help would be appreciated.

Here's what I have so far:

public static void main(String[] args) throws IOException {

String dirName = "C:\\Users\\Zed\\Desktop\\Test";
File dir = new File(dirName);
File[] files = dir.listFiles();
for(File file : files){



String s = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
if (s.contains("w = 64")) {


s = s.replace("w = 64", "w = 87.04");
try (FileWriter fw = new FileWriter(file)) {
fw.write(s);
fw.close();



} catch (FileSystemException e) {
System.out.println("Access Denied");




}
}
}
}


Success! Thank you to all who tried to help, I really appreciate it. This is the little bit of code I needed to make this work!

String[] extensions = new String[] { "ini"};
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
//File[] files = dir.listFiles();
for(File file : files){

if (file.isDirectory ()) continue;

Answer

If you have subdirectories in your dirName path, then you will be trying to write to them, so check using https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()

File[] files = dir.listFiles();
for(File file : files){
   if (file.isDirectory ()) continue;

   ....
}