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.
Related
I need to map invalid characters to some other characters like "/" to "_" (forward slash to underscore) while creating a file because file name do not allowed to put slashes, question, double quotes etc.
Suppose I have
String name = "Message Test - 22/10/2016";
Now I want to write a file by using above string but it gives error because of slashes.
So I want to map slash like all the invalid characters to any other characters while writing a file. After writing, I need to read all the names of the files & show on the page.
SOMEHOW I MAP THE CHARACTERS, SO FILE NAME WOULD BE
Message_Test_-_22-10-2016
When I show it on web I need to return file name as the original name like
Message Test - 22/10/2016
I am using java. Can anyone help me out of this how can I start writing this approach or Is there any api for it or Is there any other approach.
I don't want to use database to co-related alias file name with original file name
I need to map invalid characters to some other characters like "/" to "_"
It is not enough robust since it supposes that you never use the _ character in the filename.
If you use it, how to know if a file stored as my_file should be displayed as my_file or my/file in your application.
I think that a more reliable way would be to have a file (JSON or XML for example) that stores the two properties for each file :
the stored filename
the visual name representing it in your application
It demands an additional file but it makes things really clearer.
You can use a map to store the mappings:
E.g.
Map<Character,Character> map = new HashMap<Character,Character>();
map.put('/','_');
And then replace the characters in 1 traversal:
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if( map.containsKey(c) )
str.replace(c,map.get(c));
}
I'm working on a project that involves reading a txt file, and the way I currently have it set up is with...
reader = new BufferedReader(new FileReader(new File(url)));
...where url is a String. I don't have it set up for the user to input their own file path (or my ultimate goal to be able to choose it in a window, but that's a different matter), so I Just have url set to something like...
"file:///C:/Users/Jeremiah/Desktop/generic_text_file.txt"
My problem is that, with this technique, I can't include spaces in the file path or I'll get an invalid character exception, yet most of files and directories on a computer that a person actually deals with has spaces in it, even ones that come on the computer like "My Documents".
I've also tried passing the String through a method to escape the spaces by adding "\" in front of them, but that still isn't working.
public String escapeSpaces(String string){
int cursor = 0;
System.out.println(string);
while(cursor<string.length()){
if(string.charAt(cursor)==' '){
string = string.substring(0,cursor)+"\\"+string.substring(cursor, string.length());
System.out.println(string);
cursor++;
}
cursor++;
}
return string;
}
So how would one get around this issue so that I could instead reference a file in say...
"file:///C:/Users/Jeremiah/Desktop/S O M A N Y S P A C E S/generic_text_file.txt"
Any feedback is appreciated.
You can't construct a File with a URl string. Just pass a proper filename string directly to the constructor of File, or indeed the constructor of FileReader. There is no issue with spaces in the filename.
it still doesn't allow me to use a file path with spaces
Yes it does. You are mistaken.
escaped or not
Filenames do not require escaping. URLS require escaping. But you're just making an unnecessary mess by using the URL class.
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
// 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.
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:.*/[^/]*"/>