Search code examples
javapathnio

Java Path for Specific FileSystem


Reading the documentation on Path and other places it's obvious to me that it always takes the file system the VM is running on. However, I want to make it clear to Java that I want to have Unix-paths.

The reason is that I'm exporting paths as JSON via Jackson and there using toString() in a serializer returns different results for different VMs. In simple terms I want to get this even if I'm developing on a Windows machine:

{"path":"/tmp"}

My serializer looks like this:

public class PathSerializer extends JsonSerializer<Path> {

  @Override
  public void serialize(Path path, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
    jsonGenerator.writeString(path.toString());
  }

}

To solve it for Windows I could do this of course:

public class PathSerializer extends JsonSerializer<Path> {

  @Override
  public void serialize(Path path, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
    jsonGenerator.writeString(path.toString().replace('\\', '/'));
  }

}

But, that's not independent of the file system. I mean I know what target system I have and I don't want to cover all source systems here.

How do I do that? I mean the last resort of course is to use String instead of Path, but that's kind of lame IMHO.


Solution

  • This will work on all platforms:

    @Override
    public void serialize(Path path, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException
    {
       jsonGenerator.writeString(path.toString().replace(File.separator, "/"));
    }
    

    With the Java libraries for dealing with files, you can safely use / (slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally. That being said no matter what OS will later on read the path will be able to construct it correctly.