2

I am working in a java code that was designed to run on windows and contains a lot of references to files using windows style paths "System.getProperty("user.dir")\trash\blah". I am in charge to adapt it and deploy in linux. Is there an efficient way to convert all those paths(\) to unix style (/) like in "System.getProperty("user.dir")/trash/blah". Maybe, some configuration in java or linux to use \ as /.

3 Answers 3

3

My approach is to use the Path object to hold the path information, handle concatenate and relative path. Then, call Path's toString() to get the path String.

For converting the path separator, I preferred to use the apache common io library's FilenameUtils. It provides the three usefule functions:

String  separatorsToSystem(String path);
String  separatorsToUnix(String path);
String  separatorsToWindows(String path)

Please look the code snippet, for relative path, toString, and separator changes:

private String getRelativePathString(String volume, Path path) {
  Path volumePath = Paths.get(configuration.getPathForVolume(volume));
  Path relativePath = volumePath.relativize(path);
  return FilenameUtils.separatorsToUnix(relativePath.toString());
}
Sign up to request clarification or add additional context in comments.

Comments

2

I reread your question and realize you likely don't need help writing paths. For what you're trying to do I am not able to find a solution. When I did this in a project recently I had to take time to convert all paths. Further, I made the assumption that working out of the "user.home" as a root directory was relatively sure to include write access for that user running my application. In any case, here are some path problems I addressed.

I rewrote the original Windows code like so:

String windowsPath = "C:\temp\directory"; //no permission or non-existing in osx or linux
String otherWindowsPath = System.getProperty("user.home") + "\Documents\AppFolder";
String multiPlatformPath = System.getProperty("user.home") + File.separator + "Documents" + File.separator + "AppFolder";

If you're going to be doing this in a lot of different places, perhaps write a utility class and override the toString() method to give you your unix path over and over again.

String otherWindowsPath = System.getProperty("user.home") + "\Documents\AppFolder";
otherWindowsPath.replace("\\", File.separator);

Comments

0

Write a script, replace all "\\" with a single forward slash, which Java will convert to the respected OS path.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.