I was writing some java code that lists the files in a subdirectory on the Classpath as a stream.
InputStream is = YourClazz.class.getClassLoader().getResourceAsStream("subdirectory/")
This returns an InputStream
which I then convert into a String
.
String fileNames = "";
try (final Scanner scanner = new Scanner(is).useDelimiter("\\A")) {
fileNames = scanner.hasNext() ? scanner.next() : "";
}
I then used System.getProperty("line.seperator")
to read the lines and be platform independent.
for (String fileName : fileNames.split(System.getProperty("line.separator"))) {
// todo
}
But it failed on Windows as the delimiter in fileNames
is \n
and not line.separator
. Is this because of the Scanner
? I got this one-liner from Read/convert an InputStream to a String
Update based on answers below, I am using this code now, which works on Windows and Linux:
InputStream in = YourClazz.class.getClassLoader().getResourceAsStream("subdirectory/")
try (final Scanner scanner = new Scanner(in)) {
while (scanner.hasNextLine()) {
final String fileName = scanner.nextLine();
// todo
}
}