0

Given: a file named example.xml Aim: to test if the file example.xml.sha256 exists.

What is the most elegant/efficient way to do this in Java 7+ (nio2, so using java.nio.files)?

I have this, but it looks a little bit ugly for me:

Path path = Paths.get("/../example.xml");
if (Files.exists(Paths.get(path.toString() + ".sha256")))) {
   ...
}
rmuller
  • 12,062
  • 4
  • 64
  • 92

1 Answers1

2

It'd be a little cleaner to use .resolveSibling(), e.g.

path.resolveSibling(path.getFileName() + ".sha256");

This is not dramatically better than your solution, but it does have a few advantages:

  1. The relationship between the two files is clearly documented by the code - they're siblings, sharing the same filename prefix.
  2. It takes advantage of the features of Path - if you're just going to do direct string concatenations, you might as well not use Path at all.
  3. It avoids Paths.get(), which is a suboptimal way to work with Paths (because it assumes the default filesystem). Once you have a Path, you shouldn't ever need to re-call Paths.get().
dimo414
  • 47,227
  • 18
  • 148
  • 244
  • Okay, removed the use of `concat()` this virrvarrs the question. I know the `toString()` is redundant, but it shows why i think my solution is a little ugly. Why is your solution cleaner? – rmuller Jul 13 '15 at 20:10
  • @rmuller I added a few reasons. There's nothing wrong with string concatenations *when working with strings* (a filename on its own is a string), but when working with *paths* we can do better by taking advantage of the utilities in `Path`. – dimo414 Jul 13 '15 at 22:11