Convert String with paths denoted with dot into a filename - java

I have a properties file
{Content}
com.some.that.file.txt = com.some.dest
com.fold.cust.dir = com.some.dest
Where the key denotes the name of a directory to copy to {Value}=com.some.dest
I have replaced dots with "/" but with this i cannot retain the filename e.g file.txt becomes file/txt.

Use String.replaceAll(regex, replacement) with the right regex:
String filename = value.replaceAll("\\.(?=.*\\.)", "/");
This regex matches dots, but only if there's another dot somewhere after the matched dot, checked using a "look ahead", which has syntax (?=regex).
Here's a test:
public static void main(String[] args) {
String value = "com.some.that.file.txt";
String filename = value.replaceAll("\\.(?=.*\\.)", "/");
System.out.println(filename);
}
Output:
com/some/that/file.txt
Edited:
To find the directory names, use this:
String dirname = filename.replaceAll("/(?!.*/).*", "");
or in one line:
String dirname = value.replaceAll("\\.(?=.*\\.)", "/").replaceAll("/(?!.*/).*", "");
This extra step uses a "negative look ahead", which has syntax (?!regex), to match a slash only if there isn't a slash somewhere after the matched slash and then the regex matches everything after that using .*

Related

How to replace slashes

I want to replace a single slash with double slashes in a path, but leave double slashes unaffected.
I tried the following:
string oldPath = "\\new\new1\new2\";
string newPath = old.replace("\\", "\\\\");
My expected result is that newPath is as follows:
"\\new\\new1\\new2\\"
First of all, your oldPath is not a valid string in Java. It ends with \ which is a special character and it must be followed by something. Let's assume it should be \\ at the end.
Besides this, as #Jens mentioned in comments, \n is a new line sign, so java understands your string as \new(new_line)ew1(new_line)ew2\.
Now, if you want your result to be displayed as \\new\\new1\\new2\\ you need to use this
String newPath = old.replace("\\", "\\\\").replace("\n", "\\\\n");
Notice that the order of replace methods is important in that case.
That is because \n is interpreted as a new line. Escape one more time.
Anyways better, use java.nio.file.Path instead of String to work with files and direcory paths. Also, use System.getProperty("file.separator") to work with the file separator \ \ /.
On a unix based system, path separator is /:
/**
* Succeeds on Unix-based systems. On Windows, replace test Path and expected Path file separators
* with backslash(es).
*/
#Test
public void test() {
final Path oldPath = Paths.get("//new/new1/new2");
final String newPath = oldPath.toString().replace(System.getProperty("file.separator"),
System.getProperty("file.separator") + System.getProperty("file.separator"));
System.out.println(System.getProperty("file.separator"));
System.out.println(newPath);
assertEquals("//new//new1//new2", newPath);
}

Filter the URL path of images (img src) to obtain the file name

Using JSOUP I parse an HTML page and I've found the image path, but now I need to obtain the image file name which is a part of the url path.
For example, this is the img src:
http://cdn-6.justdogbreeds.com/images/3.gif.pagespeed.ce.MVozFWTz66.gif
The file name is 3.gif.
What shall I use to obtain the name from the URL path? Perhaps regex?
I also have other url images:
http://cdn-1.justdogbreeds.com/images/**10.gif**.pagespeed.ce.gsOmm6tF7W.gif
http://cdn-4.justdogbreeds.com/images/**6.gif**.pagespeed.ce.KbjtJ32Zwx.gif
http://cdn-2.justdogbreeds.com/images/**8.gif**.pagespeed.ce.WAWhS-Qb82.gif
http://cdn-3.justdogbreeds.com/images/**7.gif**.pagespeed.ce.UKTkscU8uT.gif
Instead of regex you can use String.lastIndexOf() with String.substring().
String imgSrc = "http://cdn-1.justdogbreeds.com/images/10.gif.pagespeed.ce.gsOmm6tF7W.gif";
String imageName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
imageName = imageName.substring(0, imageName.indexOf(".", 3));
System.out.println(imageName); // prints out 10.gif
This finds the last occurrence of forward slash ( / ), after which the image name starts. The rest of the string is the full image name. You want only the 10.gif bit, so the rest of Line 2 finds the next period after the image name.
You can use a regex replacement to get the value you need:
String filename = imgsrc.replaceAll("http://[^/]*justdogbreeds.com/images/([^/]*?\\.gif).*", "$1");
With the regex we match the whole URL, and capture the text right after the images/ and up to (including) the first .gif. The ([^/]*?\\.gif) matches 0 or more characters other than / as few as possible, and then .gif. If you have other extensions, you may either enumerate them in an alternation group (like ([^/]*?\\.(?:gif|jpe?g|png)), or use a more generic pattern [^.]+ (1 or more characters other than .):
String filename = imgsrc.replaceAll("http://[^/]*justdogbreeds.com/images/([^/]*?\\.[^.]+).*", "$1");
See IDEONE demo
String imgsrc = "http://cdn-1.justdogbreeds.com/images/10.gif.pagespeed.ce.gsOmm6tF7W.gif";
String filename = imgsrc.replaceAll("http://[^/]*justdogbreeds.com/images/([^/]*?\\.gif).*", "$1");
System.out.println(filename);

specific part of string

How can I get a specific portion of string, let suppose I have a string
file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds
and I want to get only
C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
The string is dynamic so its not always the same I just want to remove the file word from the beginning and the last portion with .ds extension
I gave it a try as
String resourceURI = configModel.eResource().getURI().toString();
//This line gives: file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds
String sourceFilePath = resourceURI.substring(6, resourceURI.length()-17)
//This line gives C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
This resourceURI.length()-17 can create problems because the SWA_Playground.ds is not always same.
How can I just remove the last portion from this string
Thanks
You should use the File class
String sourceFile = "file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds";
Sring filePath = sourceFile.substring(6);
File f = new File(filePath);
System.out.println(f.getParent());
System.out.println(f.getName());
First you remove the file:/ prefix, then you have a windows Path and you can create a File instance.
Then you use getParent() method to get the folder path, and getName() to get the file name.
Like this:
String sourceFilePath = resourceURI.substring(
resourceURI.indexOf("/") + 1, resourceURI.lastIndexOf('/') + 1);
Basically, create a substring containing everything between the first slash and the last slash.
Output will be:
C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
You need a regex:
resourceURI.replaceAll("^file:/", "").replaceAll("[^/]*$", "")
You simply want to remove everything before the first slash and after the last one?
Then do this:
String resourceURI = configModel.eResource().getURI().toString();
//This line gives: file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds
String[] sourceFilePathArray = ressourceURI.split("/");
String sourceFilePath = "";
for (int i = 1; i < sourceFilePathArray.length - 1; i++)
sourceFilePath = sourceFilePath + sourceFilePathArray[i] + "/";
//sourceFilePath now equals C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
Make use of lastIndexof() method from String class.
String resourceURI = configModel.eResource().getURI().toString();
String sourceFilePath = resourceURI.substring(6, resourceURI.lastIndexOf('.'));

java regex - matching part of string stored in variable

I need to extract up to the directory a file is in, in the folder path. To do so, I created a simple regex. Here is an example path \\myvdi\Prod\2014\10\LTCG\LTCG_v2306_03_07_2014_1226.pfd
The regex below will find exactly what I need, but my problem is storing it into a variable. This is what I have below. It fails at the string array
String[] temp = targetFile.split("\\.*\\");
folder = temp[0];
Suggestions?
Thanks!
Edit
The exception being thrown is: java.util.regex.PatternSyntaxException: Unexpected internal error near index 4
If your path is valid within your file system, I would recommend not using regex and using a File object instead:
String path = "\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
File file = new File(path);
System.out.println(file.getParent());
Output
\\myvdi\\Prod\\2014\\10\\LTCG\\
Simply, you need:
String path = "\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
String dir = path.substring(0, path.lastIndexOf("\\") + 1);
You should use Pattern & Matchers which are much more powerful; from your description I'm not sure if you want to get the whole folder path, but if it is, here is a solution:
String s = "\\\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
Pattern p = Pattern.compile("^(\\\\+[a-zA-Z0-9_-]+\\\\+([a-zA-Z0-9_-]+\\\\+)+).+$");
Matcher m = p.matcher(s);
if(m.matches()){
System.out.println(m.group(m.groupCount()-1));
}

Java String replace method doesn't replace my '\' with '/' File Finder class

my output has \.
my expected output is:
temp/F1.java
temp/F2.java
temp/subtemp/F3.java
What's wrong?..................................................................................................................................................................................................................
public class FileFinder
{
public static void main(String[] args) throws IOException
{
File dir1 = new File("temp");
dir1.mkdir() ;
File f1 = new File("temp/F1.java") ;
f1.createNewFile() ;
File f2 = new File("temp/F2.java") ;
f2.createNewFile() ;
File dir2 = new File("temp/subtemp") ;
dir2.mkdir() ;
File f3 = new File("temp/subtemp/F3.java") ;
f3.createNewFile() ;
find(dir1, ".java");
}
/**
Prints all files whose names end in a given extension.
#param aFile a file or directory
#param extension a file extension (such as ".java")
*/
public static void find(File aFile, String extension)
{
//-----------Start below here. To do: approximate lines of code = 10
// 1. if aFile isDirectory
if (aFile.isDirectory()) {
//2. use listFiles() to get an array of children files
File[] children = aFile.listFiles();
//3. use sort method of Arrays to sort the children
Arrays.sort(children);
//4. for each file in the sorted children
for (File child : children) {
//5. recurse
find(child, extension);
}
}//
else {//
//6. otherwise the file is not a directory, so
//use toString() to get the file name
String fileName = aFile.toString();
//7. use replace() to change '\' to '/'
fileName.replace('\'' , '/');
//8. if the file name endsWith the extension
if (fileName.endsWith(extension)) {
//9. then print it.
System.out.println(fileName);
}
}
//-----------------End here. Please do not remove this comment. Reminder: no changes outside the todo regions.
}
}
You need to escape the slash. Currently you're escaping a single quote instead.
Change:
fileName.replace('\'' , '/');
To:
fileName = fileName.replace('\\' , '/');
replace() doesn't change the value, you'd have to save it again which is what I did above.
this code
fileName.replace('\'' , '/');
is changing a ' to a / and to use replaceAll which uses regexp
what you want is
fileName.replaceAll("\\" , "/");
but actually - why bother with this code at all, you are not even saving the result of the replace. For that you would need
fileName = fileName.replaceAll("\\" , "/");

Categories

Resources