I’m having trouble using for-loops, and I don’t know why.
I’m using for-loops to scan a sub-folder on a directory.
Scan.java
public final void findAllMods()
{
File file = new File(path);
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
//This is the for loop im talking about
for ( String folders : directories)
{
try
{
System.out.println("REACHABLE?");
jsonPath = path + folders + "info.json"; //Value is "...Mods/everlogic"
if (workIsDone == true)
{
System.out.println(workIsDone);
workIsDone = false;
System.out.println(workIsDone);
System.out.println("REACHABLE?");
//Above code still prints
InputStream istr = new FileInputStream(getJsonPath());
String convertedJson = IOUtils.toString(istr, "UTF-8");
json = new JSONObject(convertedJson);
//Expected to print
String name = json.getString("name");
System.out.println(name);
workIsDone = true;
}
}
catch (JSONException | IOException e)
{
}
}
}
It works, and when I scan the folder name array it still works, but when I put this code inside the for-loop, it does not work
System.out.println("Reachable??");
InputStream istr = new FileInputStream(jsonpath);
String convertedJson = IOUtils.toString(istr, "UTF-8");
json = new JSONObject(convertedJson);
String name = json.getString("name");
The System.out.println(name) does not print in the console (in my case a LogCat), but the code above the InputStream executes.
I even put it in a try-catch statement also a if statement, but still doesn’t work.
Notes:
jsonisJSONObjectpathis the path to the folder with sub-foldersgetJsonPath()returns the value ofjsonPathworkIsDoneis a boolean- You need commons-io to a prevent error
- Code is made in Java 7
>Solution :
I don’t know how deep into java you are, but I’m going to assume you’re fairly new. I think the big problem is that try/catch block is stopping you from seeing that there’s an exception happening inside your for loop. I would add in e.printStackTrace(); inside the catch statement and run it again, and you’ll get more info about what’s causing your code to not work.
catch (JSONException | IOException e){
e.printStackTrace();
}
Then if an exception does show up in your console (which it probably will), look through the error message for any lines with the name of your program in it and next to it will tell you the line number that made your code stop working.