Java – reading/writing to files so it works in both a linux/windows environment

file-iojava

If someone installs my java application on their computer (windows/linux/mac), how can I make sure my applications ability to read/write files works in all environments.

Is there a way for my application to figure out where in the file system it is installed, and then read/write safely?

Note: these files that are being read/written are all application files i.e. it is not trying to reference any operating system file/registry.

So all files can be within the applications root folder (wherever it is installed)

Best Solution

Using the java.io.File (or perhaps java.nio package). This will generally work cross-platform, but you will need to be aware of platform differences and code around these. For example, you need to use things like File.pathSeparator to ensure you use the correct path separator for the platform. Also, depending on what you are doing, there are differences between how locking works etc, and not all operations are guaranteed to work - some just fail silently.

Related Question