Java NIO file path issue - java

I used the following code to get the path
Path errorFilePath = FileSystems.getDefault().getPath(errorFile);
When I try to move a file using the File NIO, I get the error below:
java.nio.file.InvalidPathException: Illegal char <:> at index 2: \C:\Sample\sample.txt
I also tried using URL.encode(errorFile) which results in the same error.

You need to convert the found resource to URI. It works on all platforms and protects you from possible errors with paths. You must not worry about how full path looks like, whether it starts with '\' or other symbols. If you think about such details - you do something wrong.
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString();

The path \C:\Sample\sample.txt must not have a leading \. It should be just C:\Sample\sample.txt

To make it work on both Windows and Linux\OS X consider doing this:
String osAppropriatePath = System.getProperty( "os.name" ).contains( "indow" ) ? filePath.substring(1) : filePath;
If you want to worry about performance I'd store System.getProperty( "os.name" ).contains( "indow" ) as a constant like
private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" );
and then use:
String osAppropriatePath = IS_WINDOWS ? filePath.substring(1) : filePath;

To be sure to get the right path on Windows or Linux on any drive letter, you could do something like this:
path = path.replaceFirst("^/(.:/)", "$1");
That says: If the beginning of the string is a slash, then a character, then a colon and another slash, replace it with the character, the colon, and the slash (leaving the leading slash off).
If you're on Linux, you shouldn't end up with a colon in your path, and there won't be a match. If you are on Windows, this should work for any drive letter.

Another way to get rid of the leading separator is to create a new file and convert it to a string then:
new File(Platform.getInstallLocation().getURL().getFile()).toString()

try to use like this C:\\Sample\\sample.txt
Note the double backslashes. Because the backslash is a Java String escape character, you must type two of them to represent a single, "real" backslash.
or
Java allows either type of slash to be used on any platform, and translates it appropriately. This means that you could type. C:/Sample/sample.txt
and it will find the same file on Windows. However, we still have the "root" of the path as a problem.
The easiest solution to deal with files on multiple platforms is to always use relative path names. A file name like Sample/sample.txt

Normal Windows Environment
Disclaimer: I haven't tested this on a normal windows environment.
"\\C:\\" needs to be "C:\\"
final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("\\C:\\","C:\\"));
Linux-Like Windows Environment
My Windows box has a Linux-Like environment so I had to change "/C:/" to be "C:\\".
This code was tested to work on a Linux-Like Windows Environment:
final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("/C:/","C:\\"));

Depending on how are you going to use the Path object, you may be able to avoid using Path at all:
// works with normal files but on a deployed JAR gives "java.nio.file.InvalidPathException: Illegal char <:> "
URL urlIcon = MyGui.class.getResource("myIcon.png");
Path pathIcon = new File(urlIcon.getPath()).toPath();
byte bytesIcon[] = Files.readAllBytes(pathIcon);
// works with normal files and with files inside JAR:
InputStream in = MyGui.class.getClassLoader().getResourceAsStream("myIcon.png");
byte bytesIcon[] = new byte[5000];
in.read(bytesIcon);

Related

Java how to handle a \ on input

I am currently trying to split a String folder. I get the value from a file system and it usually looks something like EAM\Testing.
String folder = "EAM\Testing"
String[] parts = folder.split("\\");
I know \ has special rules to it in java.
String folder = "EAM\\Testing"
String[] parts = folder.split("\\\\");
(I know the code above would work if I could control what the input looked like)
My problem is that I can not control what string folder is as input from a location of a file.
Is there a way to get this to work where folder only has one \ in it?
This is for a recycle bin component I am writing for Documentum a enterprise management system. When a document is deleted and the folder doesn't exist anymore I want to recreate it and inorder to recreate it the folder names must be seperate as I have to create them one at a time.
Here is how I get the name of the folder.
File f = new File(relationRecord.getRepeatingString(
"dp_original_folder_paths",
i));
(This gives an input such as \EAM\testing
String folder1 = f.toString();
I then get rid of the first \ by
String folder = folder1.substring(1);
Which gives me EAM\testing
Well if this is literally a file path, you should consider using the Path class, it'll make your life easier.
Path path = Paths.get("C:\\home\\joe\\foo");
System.out.format("toString: %s%n", path.toString());
System.out.format("getFileName: %s%n", path.getFileName());
System.out.format("getName(0): %s%n", path.getName(0));
System.out.format("getNameCount: %d%n", path.getNameCount());
System.out.format("subpath(0,2): %s%n", path.subpath(0,2));
System.out.format("getParent: %s%n", path.getParent());
System.out.format("getRoot: %s%n", path.getRoot());
Your second option
String[] parts = folder.split("\\\\");
Should work fine for your input string. When you write a string literal like "EAM\\Testing", the resulting string has only one slash. You can read some details on escape sequences in Java there.
The reason you need four slashes in split is because \ is an escape character both for string literals and regular expressions (String#split accepts regular expression as its argument)
You should be doing something like this -
String s = "EAM\\testing";
String a[] = s.split("\\\\");
Here you duplicate the backslash once for the String (since \ is an escape character for String) and again for the regex for the same reason.
Your question seems to be "how can I remove a leading \ from a string:
folder = folder.replaceAll("^\\\\", "");
This searches for a back slash at the start if the string, and if found replaces it with nothing (ie deletes it).
Regarding backslash vs forward slash characters in paths, java handles both.

Forward slash or backslash?

I am looking to write and read text files to and from (respectively) a directory different from that of my program. When I specify a directory to write to or read from, should I be using forward slashes or backslashes to identify a file path?
Using forward slashes will make it system independent. I'd stick to that for simplicity.
Consider using java.io.File.separator if you ever display the path to the user. You'd rather not surprise those Windows users. They're a jumpy lot.
I've never found it documented anywhere, but the JDK classes let you use slashes regardless of whether you're on Windows or not. (You can see this in the JDK source, where it explicitly converts path separators for you.)
Officially — and certainly in any UI you're doing — you should use the file.separator system property, which is available via System.getProperty(the list of standard system properties is documented in the docs for System.getProperties):
String sep = System.getProperty("file.separator");
...and also via the static fields They're also available as File.separator (and File.separatorChar).
You can also use the various features of the java.io.File class for combining and splitting paths, and/or the various features of the interfaces and classes in java.nio.file.
You could use either.
If you use / then you only need a single slash.
If you use \, you need to use \\. That is, you need to escape it.
You can also use the resolve() method of the java.nio.Path class to add directories / files to the existing path. That avoids the hassle of using forward or backward slashes. You can then get the absolute path by calling the toAbsolutePath() method followed by toString()
SSCCE:
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathSeperator {
public static void main(String[] args) {
// the path seperator for this system
String pathSep = System.getProperty("path.separator");
// my home directory
Path homeDir = Paths.get(System.getProperty("user.home"));
// lets print them
System.out.println("Path Sep: " + pathSep);
System.out.println(homeDir.toAbsolutePath());
// as it turns out, on my linux it is a colon
// and Java is using forward slash internally
// lets add some more directories to the user.home
homeDir = homeDir.resolve("eclipse").resolve("configuration");
System.out.println("Appending more directories using resolve()");
System.out.println(homeDir);
}
}
You should use /
For example C:/User/...

Java regex to replace file path based on OS

I'm not very sure there is any regex to replace thoese things:
This is a string value read from a xml file saved through Linux machine
<pcs:message schema="models/HL7_2.5.model"/>
and this is the one saved in Windows machine
<pcs:message schema="model\HL7_2.5.model"/>
This is why the file getting an error in eclipse while exported in Linux and imported in Windows or vise versa.
Is there any regex to find and replace the value(slash and back slash) within String? (not XML parsing) based on working OS?
Thanks in advance
str = str.replaceAll("\\\\|/", "\\"+System.getProperty("file.separator"))
Use the "file.separator" system property and base your regexp on that.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also see this: File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?
This should take care of fixing slashes:
String str = xml.replaceAll("\\\\|/", System.getProperty("file.separator"));

space in path using java

Hi, I have a big problem. I'm making a java program and I have to call an exe file in a folder that have whitespace. This program also has 2 arguments that always have whitspace in the path.
Example:
C:\Users\Program File\convert image\convert.exe C:\users\image exe\image.jpeg C:\Users\out put\out.bmp
I have to do this in Windows but i want generalize it for every OS.
My code is:
Runtime run = Runtime.getRuntime();<br/>
String path_current = System.getProperty("user.dir");<br/>
String [] uno = new String[]{"cmd","/c",path_current+"\\\convert\\\convert.exe",path_current+"\\\f.jpeg", path_current+"\\\fr.bmp"};<br/>
Process proc2 = run.exec(uno);<br/>
proc2.waitFor();<br/>
This does not work. I tried removing the String array and inserting a simple String with "\"" before and after the path but that didn't work. How do I resolve this?
you may want to use :
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FilenameUtils.html#separatorsToSystem(java.lang.String)
see also this answer :
Is there a Java utility which will convert a String path to use the correct File separator char?
Remove "cmd" and "/c", and use a single forward slash instead of your triple backslaches.

Java property file

I have a property file and under that I have define a property called:
config.folder = C:\myfolder\configfolder
now the problem is that when loading properties, this property returns me the vale like this:
C:myfolderconfigfolder
I want to replace this single forward slash with back slash so it return me the correct directory path. I know this is not compliance with Java.String. If the user use double forward slash I am able to convert but how can I convert single slash.
A better approach is to change the slash from backslash to forward slash, like so:
config.folder = C:/myfolde/configfolder
Java knows how to interpret this structure.
Change it to: config.folder = C:\\myfolder\\configfolder
I will suggest that you start using System Properties for this i.e. file.separator
String fileSeparator = System.getProperty("file.separator");
Now say you got the path as :
String str = "C:/myfolder/configfolder";
String fileSeparator = System.getProperty("file.separator");
str= str.replace("/", fileSeparator);
System.out.println(str);
OUTPUT is :
C:\myfolder\configfolder
This approach might help you implement your program in any OS For Example UNIX with "/" as the file separator for different components of the file path, and for WINDOWS with "\" as the file separator for components of the file path.
Hope this might help in some way.
Regards
the best way to play with the file path literal is to use the system properties i.e.string file separator =System.getProperty ("file.separator") then you can replace it with ur slash to get the file path regards

Categories