File path issue with: / -> \ - java

// Dividend Limit check or increase the Dividend
if (dival == 10) {
writer.println("Divident has reached it Limit !");
i++;
// update the file name
String upath = "channel_" + i;
System.out.println(path);
// find channel_1 and replace with the updated path
if (path.contains("channel_1")) {
path = "D:/File Compression/Data/low_freq/low_freq/house_1/"
+ upath + ".dat";
} else {
JOptionPane.showMessageDialog(null, "Invalid File Choosen");
System.exit(0);
}
dival = 10;
} else {
dival = dival + 10;
writer.println("Dividen:" + dival);
}
these lines are in a recursive method. first time it gives right path:
D:/File Compression/Data/low_freq/low_freq/house_1/channel_2.dat
But on the second call it flips the forward slash to back slash:
D:\File Compression\Data\low_freq\low_freq\house_1\channel_1.dat
it works fine if I do not use the condition.
if(path.contains("channel_"))

That is because the File.seperator in Windows is \. Every time you let your path String go through a java.io.File it will replace them. So to fix this, either don't use File as auxiliary tool, or replace the backslashes with forward slashes.
So, what happens is that your path String uses backward slashes. You retrieve that String form a java.io.File which will automatically uses backslashes on Windows. If the path contains "channel_1", then you overwrite the whole string using a hardcoded string with forward slashes.

\ is called as Escape sequence in java which is used in various purposes .
In your case use File.separator
String path = "D:"+File.separator+"File Compression"+File.separator+"Data"+File.separator+"low_freq"+File.separator+"low_freq"+File.separator+"house_1"+File.separator;
Use double slash \\ ! It's a special escape pattern. Like \n or \r.
Escape sequence normally used in text files in Windows, specially in notepad.
The primary Java escape sequences are listed below. They are used to represent non-graphical characters and also characters such as double quotes, single quotes, and backslashes. If you'd like to represent a double quote within a String literal, you can do so with \". If you'd like to represent a single quote within a character literal, you can do so with \'.

In addition to the previous answers. You should not use / or \ hard coded in your application. Because this will harm the portability of your application. rather use,
File.separator
File#separator gives you, the separator depending in your system.

Related

Regex that removes all non-alphanumeric, single periods, and single slashes

I'm trying to whitelist characters for filenames and prevent path manipulation. We take a filename returned from the frontend (i know.) and parse it to determine if it's in a specified folder. As such we need to make sure the user isn't passing in a file that could escape out of the specified folder. This means our case for a valid filename is:
Alphanumeric
Can include single slashes of either direction
Can include single dots but not pairs.
So "APP-TEST-file.20161115.1" is valid but "/../../test//\" needs to have some characters removed prior to checking the filesystem.
Here's the regex I've got now, unfortunately it's removing too much.
public static String validateFilePath(String fileName) {
return fileName.replaceAll("[^A-Za-z0-9]+[(\\.\\/)\\+2]", "");
}
Such that "APP-TEST-file.20161115.1" is becoming "APP-TEST-file0161115.1"
Any help would be appriciated.
Do you want something like this? (I am not clear about what you want!)
String filename = "APP-TEST-file.20161115.1";
// replace two consecutive dots with a single dot
filename = filename.replaceAll("\\.+", ".");
// replace two consecutive forward slash with a single forward slash
filename = filename.replaceAll("/+", "/");
// replace two consecutive baskslash with a backslash
filename = filename.replaceAll("\\\\+", "\\\\");
// allow alphanumeric characters, dots and both type of slashes
filename = filename.replaceAll("[^A-Za-z0-9./\\\\]+", "");
System.out.println(filename);
It prints:
APPTESTfile.20161115.1
If filename="/../../test//\\", then it prints - /././test/\.

Not able to read Properties File using Backward Slash

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

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.

Is there any method of JFileChooser which can provide me a file's path with Double slash "\\"?

In Netbeans I am using a JFileChooser to get a file's path. All is OK and its giving me the path as well with single slash \. But I need the path with double slash \\. So my question is, is there already any kind of method which can provide me that type of path? I also don't know the name of the path which has double slash \\. Example- H:\\New folder\\odesk\\odeskViolin4.wav
What can I do now?
You can simply replace the \ symbols with \\, by using the String.replaceAll() method.
String input = "C:\\Users\\myName"; //special characters have to be escaped.
String doubleSlashed = input.replaceAll("\\\\", "\\\\\\\\");
System.out.println(doubleSlashed);
This will print:
C:\\Users\\myName
Note that String.replaceAll(String pattern, String replacement) takes two arguments and in my example they are four-slashed and eight-slashed strings. This is because the \ symbol is a special character and has to be escaped.
Assuming you truly want to replace single backslashes with double backslashes, you could simply do this:
path = path.replace("\\", "\\\\");
However, you may not actually want double backslashes, depending on your purpose. You should at least be aware of this:
String oneBackSlash = "\\"; //This String will consist of one backslash
String twoBackSlashes = "\\\\"; //This String will consist of two backslashes
//The String below has no double backslashes, only single ones
String path = "H:\\New folder\\odesk\\odeskViolin4.wav";
System.out.println(oneBackSlash);
System.out.println(twoBackSlashes);
System.out.println(path);
Output:
\
\\
H:\New folder\odesk\odeskViolin4.wav

How to select a file path using regex

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:.*/[^/]*"/>

Categories