Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions – You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder: Reset the encoder via the reset method, unless it has not been used before; Invoke the encode method zero or more times, as long as additional input may be … Read more

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience with larger files sizes has been that java.nio is faster than java.io. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating: The buffer size. The algorithm you basically have is copy from disk to buffer copy … Read more

Java: Path vs File

Long story short: java.io.File will most likely never be deprecated / unsupported. That said, java.nio.file.Path is part of the more modern java.nio.file lib, and does everything java.io.File can, but generally in a better way, and more. For new projects, use Path. And if you ever need a File object for legacy, just call Path#toFile() Migrating … Read more

Recursively list files in Java

Java 8 provides a nice stream to process all files in a tree. Files.walk(Paths.get(path)) .filter(Files::isRegularFile) .forEach(System.out::println); This provides a natural way to traverse files. Since it’s a stream you can do all nice stream operations on the result such as limit, grouping, mapping, exit early etc. UPDATE: I might point out there is also Files.find … Read more