- Path delimiter in windows and linux for java code
- Path delimiter in windows and linux for java code
- How to split a path platform independent?
- Escape path separator in a regular expression
- Is there a Java utility which will convert a String path to use the correct File separator char?
- Get file path separator in Java
- 2. Get a file path separator using a system property
- 3. Retrieve path separator with FileSystems.getDefault().getSeparator() method
- 4. File path separator using Java IO File.separator
- 5. Conclusion
Path delimiter in windows and linux for java code
Solution 4: Create an empty list and use forEach to iterate over the path elements inserting each one into the list for later use: Also, if you need a specific path element use: where is returned by a call to , and if you need multiple parts of the path returned in a string use: You can get the total number of path elements (for use in ) with: There are other useful methods at the Java Path and Paths doc pages. Path implements , so you can do: Methods getNameCount
Path delimiter in windows and linux for java code
In my java code, I have some hard coded paths which I have written as
String workingPath = initPath + "\\" + tmpPath;
the initPath and tmpPath are obtained by File.getParent() . Now, that works on windows and if I move my code to linux, the \\ will be problematic since the other two are determined by system methods. The results is something like this
/home/mahmood/project/alpha\temp1
How can I fix that? I don’t want to put / in my code for linux systems.
There is a variable you can use: File.separator
The system-dependent default name-separator character, represented as a string for convenience. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this field is ‘/’; on Microsoft Windows systems it is ‘\’.
String workingPath = initPath + File.separator + tmpPath;
The File class has a constructor that accepts a parent directory. If you use this, you don’t need to manually concatenate paths.
final File parent = new File("/home/mahmood/project/alpha"); final File tmp = new File(parent, "temp1");
Java — When should I use File.separator and when, You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this: String path = File.separator + «var»+ File.separator + «temp». You use the pathSeparator when you are dealing with a list of files like in a classpath.
How to split a path platform independent?
I’m using the following code to get an array with all sub directories from a given path.
String[] subDirs = path.split(File.separator);
I need the array to check if certain folders are at the right place in this path. This looked like a good solution until findBugs complains that File.separator is used as a regular expression. It seems that passing the windows file separator to a function that is building a regex from it is a bad idea because the backslash being an escape character.
How can I split the path in a cross platform way without using File.separator? Or is code like this okay?
String[] subDirs = path.split("/");
Literalizing pattern strings
Whenever you need to literalize an arbitrary String to be used as a regex pattern, use Pattern.quote :
public static String quote(String s)
Returns a literal pattern String for the specified String . This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning.
Parameters: s — The string to be literalized
Returns: A literal string replacement
This means that you can do the following:
String[] subDirs = path.split(Pattern.quote(File.separator));
Literalizing replacement strings
If you need to literalize an arbitrary replacement String , use Matcher.quoteReplacement .
public static String quoteReplacement(String s)
Returns a literal replacement String for the specified String . This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ( ‘\’ ) and dollar signs ( ‘$’ ) will be given no special meaning.
Parameters: s — The string to be literalized
Returns: A literal string replacement
This quoted replacement String is also useful in String.replaceFirst and String.replaceAll :
Note that backslashes ( \ ) and dollar signs ( $ ) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Use Matcher.quoteReplacement to suppress the special meaning of these characters, if desired.
Examples
System.out.println( "O.M.G.".replaceAll(".", "!") ); // prints ". " System.out.println( "O.M.G.".replaceAll(Pattern.quote("."), "!") ); // prints "O!M!G!" System.out.println( "Microsoft software".replaceAll("so", "$0") ); // prints "Microsoft software" System.out.println( "Microsoft software".replaceAll("so", Matcher.quoteReplacement("$0")) ); // prints "Micro$0ft $0ftware"
Use path.getParentFile() repeatedly to get all components of a path.
Discouraged way would be to path.replaceAll(«\\», «/»).split(«/») .
java.nio.file.Path implements Iterable , so you can do:
public static void showElements(Path p) < ListnameElements = new ArrayList<>(); for (Path nameElement: p) nameElements.add(nameElement.toFile().getName()); System.out.printf("For this file: [%s], the following elements were found: [%s]\n" , p.toAbsolutePath() , Joiner.on(", ").join(nameElements)); >
Methods getNameCount and getName can be used for a similar purpose.
Create an empty list and use forEach to iterate over the path elements inserting each one into the list for later use:
List pathElements = new ArrayList<>(); Paths.get("/foo/bar/blah/baz").forEach(p -> pathElements.add(p.toString()))
Also, if you need a specific path element use:
where is returned by a call to Paths.get() , and if you need multiple parts of the path returned in a string use:
You can get the total number of path elements (for use in ) with:
There are other useful methods at the Java Path and Paths doc pages.
How to use java.nio.file.Path with file separator?, I am trying to set up a simple test web server in Java but when I create a Path object the result is with backslashes instead of forward slashes which I think is causing it to return a 404. Is there a way to use «file.separator» with a Path object? Check filepath & return response
Escape path separator in a regular expression
I need to write a regular expression that finds javascript files that match
For example, it should work for both :
The problem is that the File separator in Windows is not being properly escaped :
pattern = Pattern.compile( "^(.+?)" + File.separator + "js" + File.separator + "(.+?).js$" );
java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence
Is there any way to use a common regular expression that works in both Windows and UNIX systems ?
Does Pattern.quote(File.separator) do the trick?
EDIT: This is available as of Java 1.5 or later. For 1.4, you need to simply escape the file separator char:
Escaping punctuation characters will not break anything, but escaping letters or numbers unconditionally will either change them to their special meaning or lead to a PatternSyntaxException. (Thanks Alan M for pointing this out in the comments!)
Is there any way to use a common regular expression that works in both Windows and UNIX systems ?
Yes, just use a regex that matches both kinds of separator.
pattern = Pattern.compile( "^(.+?)" + "[/\\\\]" + "js" + "[/\\\\]" + "(.+?)\\.js$" );
It’s safe because neither Windows nor Unix permits those characters in a file or directory name.
Can’t you just use a backslash to escape the path separator like so:
pattern = Pattern.compile( "^(.+?)\\" + File.separator + "js\\" + File.separator + "(.+?).js$" );
Why don’t you escape File.separator :
to fit Pattern.compile requirements? I hope «/» (unix case) is processed as a single «/».
File — Does Java have a path joining method?, 4 Answers. This concerns Java versions 7 and earlier. If you want it back as a string later, you can call getPath (). Indeed, if you really wanted to mimic Path.Combine, you could just write something like: public static String combine (String path1, String path2) < File file1 = new File (path1); File file2 = new File (file1, path2); …
Is there a Java utility which will convert a String path to use the correct File separator char?
I have developed a number of classes which manipulate files in Java. I am working on a Linux box, and have been blissfully typing new File(«path/to/some/file»); . When it came time to commit I realised some of the other developers on the project are using Windows. I would now like to call a method which can take in a String of the form «/path/to/some/file» and, depending on the OS, return a correctly separated path.
For example:
«path/to/some/file» becomes «path\\to\\some\\file» on Windows.
On Linux it just returns the given String.
I realise it wouldn’t take long to knock up a regular expression that could do this, but I’m not looking to reinvent the wheel, and would prefer a properly tested solution. It would be nice if it was built in to the JDK, but if it’s part of some small F/OSS library that’s fine too.
Apache Commons comes to the rescue (again). The Commons IO method FilenameUtils.separatorsToSystem(String path) will do what you want.
Needless to say, Apache Commons IO will do a lot more besides and is worth looking at.
A «/path/to/some/file» actually works under Windows Vista and XP.
new java.io.File("/path/to/some/file").getAbsoluteFile() > C:\path\to\some\file
But it is still not portable as Windows has multiple roots . So the root directory has to be selected in some way. There should be no problem with relative paths.
Apache commons io does not help with envs other than unix & windows. Apache io source code:
public static String separatorsToSystem(String path) < if (path == null) < return null; >if (isSystemWindows()) < return separatorsToWindows(path); >else < return separatorsToUnix(path); >>
This is what Apache commons-io does, unrolled into a couple of lines of code:
String separatorsToSystem(String res) < if (res==null) return null; if (File.separatorChar=='\\') < // From Windows to Linux/Mac return res.replace('/', File.separatorChar); >else < // From Linux/Mac to Windows return res.replace('\\', File.separatorChar); >>
So if you want to avoid the extra dependency, just use that.
With the new Java 7 they have included a class called Paths this allows you to do exactly what you want (see http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html)
String rootStorePath = Paths.get("c:/projects/mystuff/").toString();
Path delimiter in windows and linux for java code, There is a variable you can use: File.separator. The system-dependent default name-separator character, represented as a string for convenience. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this field is ‘/’; on Microsoft …
Get file path separator in Java
In this article, we will present how to get a file path separator in Java. A file separator is platform-dependent what means in Unix we will have a different separator than in Windows OS. That’s why it is important to use Java-built methods to retrieve it when we are working with files.
We can get file path separator in three ways:
- using System.getProperty(«file.separator») ,
- with FileSystems.getDefault().getSeparator() method from the latest Java NIO,
- using File.separator from Java IO API.
2. Get a file path separator using a system property
In system properties JVM holds information about the configuration of the current working environment such as a current version of Java runtime («java.version»), current user («user.name»), and also the character used to separate elements of the file pathname («file.separator»).
Let’s check the example code that makes use of that system properties to get file path separator:
package com.frontbackend.java.io.separator; public class FilePathSeparatorFromSystemProperty < public static void main(String[] args) < String pathSeparator = System.getProperty("file.separator"); System.out.println(pathSeparator); // in Unix /, in Windows \ >>
Note that System.getProperties() can be overridden using System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/ , so we could not rely on this parameter in 100%.
3. Retrieve path separator with FileSystems.getDefault().getSeparator() method
Another method to get a file path separator comes with Java NIO API. This API provides a dedicated method called on FilesSystems class to get the name of the separator used to separate names in a path string.
The following example shows how to use a platform-independent method from Java NIO to get a file path separator:
package com.frontbackend.java.io.separator; import java.nio.file.FileSystems; public class FilePathSeparatorUsingJavaNIO < public static void main(String[] args) < String pathSeparator = FileSystems.getDefault() .getSeparator(); System.out.println(pathSeparator); // in Unix / , in Windows \ >>
4. File path separator using Java IO File.separator
In older Java IO API there is also a property that holds a file path separator File.separator :
package com.frontbackend.java.io.separator; import java.io.File; public class FilePathSeparatorUsingJavaIOAPI < public static void main(String[] args) < String pathSeparator = File.separator; System.out.println(pathSeparator); // Unix / , Windows \ >>
We recommend using the FileSystems.getDefault().getSeparator() method that was provided in Java NIO.
5. Conclusion
This article covered methods used to get a file path separator in Java. It is important to use methods available in Java IO or NIO API, instead of hardcoded values. This will prevent unexpected exceptions and errors when working with files in Java applications.
As always code snippets used in this article are available under the GitHub repository.