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
Related
I Am not able to read Properties File using Java.It Means In this Properties File Backward Slash is not working.It is showing like ,this destination :C:Usersxxx.a
String filename="D://Desktop//xxx.properties";
is = new FileInputStream(filename);
Properties prop=new Properties();
prop.load(is);
System.out.println("destination :"+prop.getProperty("destination"));
Property File is the :
destination=C:\Users\xxx.a\
Result is showing
destination :C:Usersxxx.a
But I want to show destination :C:\Usersxxx.a\
Can You Please suggest Me?
\ is an Escape character.
forward slash / is used as path separator in Unix environment.
Back slash \ is used as path separator in Windows environment.
So, You need to use \\ or / as path separator. You can not directly use \ in java. Since, it is an escape character.
So,You need to make changes in your properties file to make your program work.
Use either / or \\ as path separator in your properties file.
In your case you want to show as C:\Users\xxx.a\.
So, use C:\\Users\\xxx.a\\ in your properties file to get output as C:\Users\xxx.a\
The \ character is used as an "escape character" in many programming languages. It gives a special meaning to the next character in the text. For example, \n encodes the special character "new-line".
Use \\ instead of \. This indicates to the parser that you mean the actual symbol, not an escape character. For example, your property value would be:
destination=C:\\Users\\xxx.a\\
You need to add two slashes to your properties file like this:
destination=C:\\Users\\xxx.a\\
The other way is to swap the slashes in the properties file:
destination=C:/Users/xxx.a/
A \ is an escape character so it is removed. Adding two slashes escapes the first so only one is left.
You can store it in D:/Desktop/xxx.properties as
destination=C:/Users/xxx.a/
and show it with a single backslash
String fileName = prop.getProperty("destination");
System.out.println("destination: " + fileName); // shows: C:/Users/xxx.a/
System.out.println("destination: " + Paths.get(fileName)); // shows: C:\Users\xxx.a
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"));
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.
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);
I would like like to create a java regular expression that selects everything from file: to the last forward slash (/) in the file path. This is so I can replace it with a different path.
<!DOCTYPE "file:C:/Documentum/XML%20Applications/joesdev/goodnews/book.dtd"/>
<myBook>cool book</myBook>
Does anyone have any ideas? Thanks!!
You just want to go to the last slash before the end-quote, right? If so:
file:[^"]+/
(the string "file:", then anything but ", ending with a /)
Properly escaped:
String regex = "file:[^\"]+/";
You could try to process this yourself, but a better scheme would be to just pick out the parts between the quotes and use java.util.File to separate the directory name from the filename. That way you don't have to worry about / vs \ or various escape characters.
String newPath = "C:/Documentum/badnews";
String originalPath = "<!DOCTYPE \"file:C:/Documentum/XML%20Applications/joesdev/goodnews/book.dtd\"/>";
System.out.println(originalPath.replaceFirst("file:C:((/[/\\w%]+))", newPath));
Try this:
"file:.*/[^/]*"/>