How to retrieve particular part of string - java

I have got a directory listing as a String and I want to retrieve a particular part of the string, the only thing is that as this is a directory it can change in length
I want to retrieve the file name from the string
"C:\projects\Compiler\Compiler\src\JUnit\ExampleTest.java"
"C:\projects\ExampleTest.java"
So in these two cases I want to retrieve just ExampleTest (the filename can also change so i need something like get the text before the first . and after the last \). Is there a way to do this using something like regex or something similar?

Why not use Apache Commons FileNameUtils rather than coding your own regular expressions ? From the doc:
This class defines six components within a filename (example
C:\dev\project\file.txt):
the prefix - C:\
the path - dev\project\
the full path - C:\dev\project\
the name - file.txt
the base name - file
the extension - txt
You're a lot better off using this. It's geared directly towards filenames, dirs etc. and given that it's a commonly used, well-defined component, it'll have been tested extensively and edge cases ironed out etc.

new File(thePath).getName()
or
int pos = thePath.lastIndexOf("\\");
return pos >= 0? thePath.substring(pos+1): thePath;

File file = new File("C:\\projects\\ExampleTest.java");
System.out.println(file.getAbsoluteFile().getName());

Java code
String test = "C:\\projects\\Compiler\\Compiler\\src\\JUnit\\ExampleTest.java";
String arr[] = test.split("\\Q"+"\\");
System.out.println(arr[arr.length-1].split("\\.")[0]);

This is the regex in c# and it works in java :P too.Thanks to Perl.It matches in Group[1]
^.*\\(.*?)\..*?$

Related

How to get only filename without .mp3 and .mp4 extension in android?

I have audio and video names like this :
- azan1(1).mp3
- Funny.mp4
So I need an only AudioName as azan and VideoName as Funny. I am newbie in android and don't know how can I get only filename? How can I achieve this in code.??
Try this way to get filename without extension:-
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
In Java , simple and efficient way to get the filename
String resultName= filename.split("\\.")[0].split("\\(")[0];
As mentioned by 44kksharma, you can split the String at the . to get the extension. The only problem as I can see is if the file name contains . elsewhere (for an instance filename.test.mp3) - the file is an mp3 but one could argue filename.test is a part of the file name. If you think of it like that, this is the right approach using splitting:
String resultName = filename.split("\\.mp")[0];
If you have other extensions, you can do this:
String resultName = filename.split("\\.mp|\\.wav|\\.otherformat")[0];
mp3 and mp4 with have mp in them, therefore files with either extension is guaranteed to have .mp.
Using | is or in regex.
Alternatively, you can use the replaceAll method:
String result = filename.replaceAll("\\.mp3|\\.mp4", "");
replace works too, but as it doesn't use regex I find it ends up replacing the wrong chars or ends up screwing up the replacement.
Finally, you could use substring too, but using one-liners is possible with regex(/non-regex using replace) with split(), replace() and replaceAll()
if(audioname.contions(.mp3)
{
String audiostr= audioname.replace(".mp3", "");
}
if(videoname.contions(.mp4)
{
String videostr= videoname.replace(".mp3", "");
}
Set the String in your required textview

Merging two relative file URLs

Let' say I have two paths, first can look like folder/ and second like /anotherFolder/image.png. I would like to merge those two paths in some automated fashion and with option for user to omit the last slash in first string and first slash in second string. So all of these
folder/ + /anotherFolder/image.png
folder + anotherFolder/image.png
folder + /anotherFolder/image.png
should give me folder/anotherFolder/image.png
I need to merge two properties in one of my projects and I want it as dummy as possible:)So is there some trick with URL class or do I have to play around with Strings?
You can do this with java.io.File, by using the constructor which takes a File and a String as arguments, will interpret the String as a relative path to the File.
Or with java.net.URL, you can send an URL and a String to the constructur, which will interpret the URL as a context for the String parameter.
I actually used FileUtils.getFile() from Apache Commons IO but Rolf's solution was working too.

Java - How to get the name of a file from the absolute path and remove its file extension?

I have a problem here, I have a String that contains a value of C:\Users\Ewen\AppData\Roaming\MyProgram\Test.txt, and I want to remove the C:\Users\Ewen\AppData\Roaming\MyProgram\ so that only Test is left. So the question is, how can i remove any part of the string.
Thanks for your time! :)
If you're working strictly with file paths, try this
String path = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
File f = new File(path);
System.out.println(f.getName()); // Prints "Test.txt"
Thanks but I also want to remove the .txt
OK then, try this
String fName = f.getName();
System.out.println(fName.substring(0, fName.lastIndexOf('.')));
Please see this for more information.
The String class has all the necessary power to deal with this. Methods you may be interested in:
String.split(), String.substring(), String.lastIndexOf()
Those 3, and more, are described here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Give it some thought, and you'll have it working in no time :).
I recommend using FilenameUtils.getBaseName(String filename). The FilenameUtils class is a part of Apache Commons IO.
According to the documentation, the method "will handle a file in either Unix or Windows format". "The text after the last forward or backslash and before the last dot is returned" as a String object.
String filename = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
String baseName = FilenameUtils.getBaseName(filename);
System.out.println(baseName);
The above code prints Test.

Remove file prefix in absolute path but prefix is also directory part

I was wondering if there is any nice solution for the following problem:
Assuming I have a string with the absolute Path to a file and the file has the prefix "temp_".
I am able to trim the prefix with string.replaceFirst().
But if I am unlucky "temp_" is also part of the directory in that String.
How to make sure only the last occurence will get trimmed?
I can only think to parse it myself, but was wondering if there's magic left to do it a better way?
To be more precisely as example:
C:\Dump\sol1\temp_results\temp_2012-04-core.pcap
Should become:
C:\Dump\sol1\temp_results\2012-04-core.pcap
If you use Path.getFileName(), only the base name of the file is returned (ie, it does not include any parent directory). You can do your substitution with that and put it back together using other Path functions (see getName(), subpath(), etc) into either another Path or a single String.
if you have got it is a File id defo use #goldilocks' approach. But if for some reason you simply have it as a String, first thing that popped into my head is this:
String target = "temp_";
String fullPath = "C:/Dump/sol1/temp_results/temp_2012-04-core.pcap";
StringBuffer sb = new StringBuffer(fullPath);
int end = fullPath.lastIndexOf(target) + target.length();
System.out.println(sb.replace(fullPath.lastIndexOf(target), end, ""));
This is just another example How to do it.
devide total String into three parts.
1.substring till temp_ last occurence
2.last occuerence of temp_
3.substring after last occuerence of temp_
cancat 1+3 anyway I recommend #goldilocks solution

Working with files with anchors, which options are there for Java?

I am working with files (reading, writing and copying) in my Java application, java.io.File and commons-io were perfect for this kind of tasks.
Right now, I can link to HTML in this way:
Z:\an absolute\path\to\a\file.html
But, I need to provide support for anchors too:
Z:\an absolute\path\to\a\file.html#anchor
keeping the system-independence obtained by using java.io.File. So, I will need to extract the path and the anchor, I wonder whether it will be as easy as searching for a sharp occurrence.
java.io.File includes a constructor that accepts a URI, which can represent all kinds of resources, included URLs and local files (see the rfc). URI's also meets your requirements of supporting anchors, and extracting path information (through instance.getPath()).
File f = new File("Z:\\path\\to\\a\\file.html#anchor");
String anchor = f.toURL().getRef(); //note: toURL is deprecated
If you look at the java source you will see that it is as simple as:
String file = "Z:\\path\\to\\a\\file.html#anchor";
int ind = file.indexOf('#');
String anchor = ind < 0 ? null: file.substring(ind + 1);

Categories