This question already has answers here:
java split function
(6 answers)
Closed 7 years ago.
I need to rename some paths in database.
I rename folder:
String mainFolder= "D:\test\1\data"; //folder renamed from fd
Then i need to rename all files and directories inside that folder:
String file1="D:\test\1\fd\dr.jpg";
String folder1="D:\test\1\fd\fd"; // in this case last fd needs to be renamed
String folder2="src/fd/fd/"; //fake path also needs to be renamed
What is the best and fastest way to rename that strings?
My thoughts about "/":
String folder2= "src/da/da";
String[] splittedFakePath = folder2.split("/");
splittedFakePath[splittedFakePath.length - 2] = "data";
StringBuffer newFakePath = new StringBuffer();
for (String str : splittedFakePath) {
newFakePath.append(str).append("/");
}
String after rename: src/data/da/
But when im trying split by "\":
Arrays.toString(Pattern.compile(File.separator).split(folder1));
I receive:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
Look into java's String replace(...) method.
It is wonderful for string replacement, much better than attempting a regex.
Keep in mind that real directory handling has a few special cases, which don't lend themselves well to direct string manipulation. For example '//' often gets compacted to '/' in Unix like systems, and if you care about proper directory corner-cases, then use the Java Path class
Related
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.
This question already has answers here:
How do I get the file name from a String containing the Absolute file path?
(13 answers)
Closed 7 years ago.
I'm trying to slpit the string /home/user/test.dat
I use String[] split = file.split("(?!.*/)"); but split[1] only returns the first character instead of the whole file name. How would I edit my regex so that it returns everything past the last forward slash?
Unless there's some compelling reason to use a regular expression, I would use the simple String.lastIndexOf(int). Something like,
String file = "/a/b/c/d/e/test.dat";
int afterSlash = file.lastIndexOf('/');
if (afterSlash > -1) {
file = file.substring(afterSlash + 1);
}
System.out.println(file);
Output of above being (the requested)
test.dat
Regex
\/((\w+)\.(\w+))$
Debuggex Demo
However, since you are using Java simply load the string into the File helper which can pull out the filename:
Java
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();
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.
This question already has answers here:
Java: splitting a comma-separated string but ignoring commas in quotes
(12 answers)
Closed 9 years ago.
I have a problem with splitting a sentence in Java
input string :
"retinol,\"3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid\",C034534,81485-25-8,\"Carcinoma, Hepatocellular\",MESH:D006528,Cancer|Digestive system disease,,17270033,therapeutic";
and i want to split it and get splitted terms like as follows ;
retinol
3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid
C034534
81485-25-8
Carcinoma, Hepatocellular
MESH:D006528
Cancer|Digestive system disease
(nothing)
17270033
therapeutic
I tried few way to solve this problem such as Pattern/Matcher and split(",")[] etc..
But, i couldn't find the answer..
As discussed in the comments, since you're parsing a CSV file, you're going to want to use a library specifically written to parse CSVs. Otherwise you'll continue to run into problems where what you write is "useless when a different patten comes out" (as you said).
However, to solve the question at hand you just have to split on a comma, ignoring commas inside of quotes. So you can do this (from this answer):
String input = "retinol,\"3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid\",C034534,81485-25-8,\"Carcinoma, Hepatocellular\",MESH:D006528,Cancer|Digestive system disease,,17270033,therapeutic";
String[] output = input.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for(String s : output){
System.out.println(s);
}
This will give you this output (note the quotes and empty line):
retinol
"3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid"
C034534
81485-25-8
"Carcinoma, Hepatocellular"
MESH:D006528
Cancer|Digestive system disease
17270033
therapeutic
You can replace the quotes and ignore the empty line as you wish. This loop will print the exact output requested in the question:
int i=1;
for(String s : output){
if(!s.isEmpty()){
System.out.println(i++ + ". " + s.replace("\"", ""));
}
}
Output:
retinol
3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid
C034534
81485-25-8
Carcinoma, Hepatocellular
MESH:D006528
Cancer|Digestive system disease
17270033
therapeutic
But, please, use a library like OpenCSV.
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.