When such a problem arises, and you have been diving deep into something, and spend too much time with one issue: always take a step back, take a break, do something else, and come back later... It pays off.
Your code is almost right
for (String file: fileNames){ //logically OK
String url = path + file;
for (int i = 0; i < urls.length; i++) { //things start going wrong
urls[i] = url; //this line has a red underline
}
}
You have 2 problems: a logical one, and a minor issue.
The minor problem:
This line is incorrect:
urls[i] = url;
The array urls is of type URL - which is not a supertype of String, so this line is most likely red in your IDE. To correct it, we need to create an URL instance from the String, and we are lucky: there is a constructor exactly for that: new URL(url). However, this can throw a MalformedUrlException if there is a problem which needs to be caught. For the sake of simpleness, let's just rethrow it as an IllegalStateException
try {
urls[i] = new URL(url);
} catch (MalformedUrlException e) {
throw new IllegalStateException("Wrong URL: " + url);
}
The logical problem:
While going through the filenames, on each iteration you also iterate over the whole urls[] array I think you don't want that: each filename will yield one URL - so it should be enough to traverse the filename array once. Also, by setting the value on each iteration - you would overwrite all previous values, and when all the loops complete, all you would be left with is an array filled with the last URL processed.
I think the problem you try to solve with the inner loop is that you don't know which index to put the new element into, because you didn't keep track which filename entry you were processing. This is a scenario, where a traditional for loop is more handy than just iterating over the array:
for (int i = 0; i < fileNames.length; i++){
String file = fileNames[i];
String url = path + file;
try {
urls[i] = new URL(url);
} catch (MalformedUrlException e) {
throw new IllegalStateException("Wrong URL: " + url);
}
}
Of course, this can be improved to be a bit shorter:
for (int i = 0; i < fileNames.length; i++){
try {
urls[i] = new URL(path + fileNames[i]);
} catch (MalformedUrlException e) {
throw new IllegalStateException("Wrong URL: " + path + fileNames[i]);
}
}
... and of course the exception would need an appropriate handling, but that requires more in-depth knowledge about what the code is trying to do, e.g. is it considered an irrecoverable error if the URL is incorrect, etc.