Reputation: 11
I am backporting a code to Java SE6 and I am looking to have a OS agnostic file retrieval for my code. I already have a code on SE7 that works great.
This is the way I am using it on Java SE7.
protected Properties getPropertiesFromFileSystemPath(final String filename) throws IOException {
if (filename != null) {
Path p = FileSystems.getDefault().getPath("");
final InputStream inputStream = new FileInputStream(p.resolve(filename).toFile());
return getProperties(inputStream);
} else {
throw new IOException();
}
}
With this code I can point to a file foo\bar\file.txt
or foo/bar/file.txt
and will be found.
Is there is an alternative way as easy as using java.nio.file.Path
in Java SE6?
Upvotes: 1
Views: 491
Reputation: 630
If you are receiving aways a single file, using this Path concat function is an overkill.
You can use simply new FileInputStream(filename)
. It will work correctly on both /
and \
, even if you mix them up.
And it is very important that you CLOSE the input stream you opened. In java7 you can use the autocloseable function:
try (InputStream is = new FileInputStream(filename)) {
return getProperties(is);
}
In Java6 you need to close it yourself:
InputStream is = new FileInputStream(filename);
try {
return getProperties(is);
} finally {
if (is != null) is.close();
}
Upvotes: 1