8

I am in a refactoring stage for a project I am working on and would like to make some improvements to how I build and represent file system paths. What things should I take into consideration when representing relative paths in Java code to ensure compatibility on Ubuntu, OSX, and Windows 7.

Currently to get an instance of File referencing "MyProject/foo/bar.f" I would have code along the lines of:

File bar = new File(ProjectDirectory + "/" + FooResourceDirectory + "/" + barName);

This seems wrong for several reasons, what are some of the best practices?

2 Answers 2

12

Perhaps use the constructors provided to do this sort of thing:

new File(parent, child) 

You have to "nest" them, but it's trivial to handle this (e.g. make a function to get a path built from something taking string....)

See the File constructors.

Sign up to request clarification or add additional context in comments.

1 Comment

File.pathSeparator is part what I was originally looking for, but I think I like the idea of using the built in constructors, and nesting/having a wrapper function more.
9

First of all you should use File.separator File.pathSeparator instead of "/".

3 Comments

Attention: File.pathSeparator != File.separator -- File.pathSeparator (for example "/")is the character to separate parts of one path, and File.separator (for example ";") is the character to separate different Paths
I prefer to use the correct constructor through: new File(parent, child)
@Ralph i think you mixed that up. ";" <-> "/"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.