Dynamic String get dynamic image name in java - java

i have a dynamic String like
age/data/images/four_seasons1.jpg
from above string i need to get the image name alone (i.e.) four_seasons1.jpg
the path and the image will be a dynamic one(any image format will occure)
Please let me know how to do this in java?
thanks in advance

Use the File Object.
new File("/path/to/file").getName()
You could also use String.split().
"/path/to/file/sdf.png".split("/")
This will give you an array in which you pick the last element. But the File Object is better suited.

String text = "age/data/images/four_seasons1.jpg";
String name = text.substring(text.lastIndexOf("/") + 1);
String path = text.substring(0, text.lastIndexOf("/"));
System.out.println(name);
System.out.println(path);
Outputs
four_seasons1.jpg
age/data/images
Take some time and become familiar with the java.lang.String API. You'll be doing this kind of stuff a lot

You can go for regex but if you find the pattern is fixed, A very crude solution can be a straight forward approach
String url = "age/data/images/four_seasons1.jpg";
String imageName = url.substring(url.lastIndexOf( "/" )+1, url.length()) ;

You can parse this path. As a delimiter you must take '/' symbol. After that you can take last parsed element.
String phrase = "age/data/images/four_seasons1.jpg";
String delims = "/";
String[] tokens = phrase.split(delims);
About String.split you can read more here.

String s = "age/data/images/four_seasons1.jpg";
String fileName = new String();
String[] arr = s.split("/");
fileName = arr[arr.length-1];
}

Related

Regex to extract the filename and drop the file timestamp from complete path in Java

i have complete file path and i just need to extract the filename and just extension. So my output would be fileName.csv.
For ex: complete path is:
/Dir1/Dir2/Dir3/Dir4/Dir5/Dir6/fileName_20150108_002_20150109013841.csv
My output of Regex should be fileName.csv.
Extension and level of directories are not fixed.
As part of my requirement i need single regex that can extract fileName.csv not fileName_20150108_002_20150109013841.csv.how can i do it in single regular expression ?
Without using regex this can be solved as -public static String getFileName(String args){
args = args.substring(args.lastIndexOf('/')+1);
return args.substring(0,args.indexOf('_')) + args.substring(args.indexOf('.'));
}
Below would work for you might be
[^\\/:*?"<>|\r\n]+$
This regex has been tested on these two examples:
\var\www\www.example.com\index.jsp
\index.jsp
or rather you should use File.getName() for better approach.
String filename = new File("Payload/brownie.app/Info.plist").getName();
System.out.println(filename)
another way is
int index = path.lastIndexOf(File.separatorChar);
String filename = path.substring(index+1);
finally after getting the full filename use below code snippet
String str = filename;// in your case filename will be fileName_20150108_002_20150109013841.csv
str = str.substring(0,str.indexOf('_'))+str.substring(str.lastIndexOf('.'));
System.out.println("filename is ::"+str); // output will be fileName.csv
In the below code, group one will be fileName_timestamp.extension. I've replaced numerics and underscores with empty string. This may look ugly, but still will server your purpose. If the file name contains numerics, we need go for a different approach.
public static void main(String[] args) {
String toBeSplitted = "/Dir1/Dir2/Dir3/Dir4/Dir5/Dir6/fileName_20150108_002_20150109013841.csv";
Pattern r = Pattern.compile("(/[a-zA-Z0-9_.-]+)+/?");
Matcher m = r.matcher(toBeSplitted);
if(m.matches()){
String s = m.group(1).replaceAll("(/|[0-9]|_)", "");
System.out.println(s);
}
}

Java Replacing Help Needed

Hey guy's so am trying to replace all characters and numbers to get the /hello/what/ only without the REMOVEThis4.PNG i don't want to use string.replace("REMOVEThis4.PNG", ""); cause i wanna use it on other strings not only that
Any help is great my code
String sFile = "/hello/what/REMOVEThis4.PNG";
if (sFile.contains("/")){
String Replaced = sFile.replaceAll("(?s)", "");
System.out.println(Replaced);
}
I want the the output to be
/hello/what/
Only thanks alot!
If you are trying to parse a path, I recommend to find the last index of /, and get the substring to this index plus one. So
string = string.substring(0, string.lastIndexOf("/") + 1);
No need to use regular expressions in your case:
String sFile = "/hello/what/REMOVEThis4.PNG";
// TODO check actual last index of "/" against -1
System.out.println(sFile.substring(0, sFile.lastIndexOf("/") + 1));
Output
/hello/what/
Note
In case you are dealing with actual files, you can probably spare yourself the String manipulation and use File.getParent() instead:
File file = new File("/hello/what/REMOVEThis4.PNG");
System.out.println(file.getParent());
Output (may change depending on your system)
\hello\what
Use Java's File API:
String example = "/hello/what/REMOVEThis4.PNG";
File file = new File(example);
System.out.println(example);
String absolutePath = file.getAbsolutePath();
String filePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
System.out.println(filePath);

How to concatenate string or word inside each String index

I am having trouble encoding a url with combined Non-ASCII and spaces. For example, http://xxx.xx.xx.xx/resources/upload/pdf/APPLE ははは.pdf. I've read here that you need to encode only the last part of the path of the url.
Here's the code:
public static String getLastPathFromUrl(String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
So now I have already APPLE ははは.pdf, next step is to replace spaces with %20 for the link to work BUT the problem is that if I encode APPLE%20ははは.pdf it becomes APPLE%2520%E3%81%AF%E3%81%AF%E3%81%AF.pdf. I should have APPLE%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf.
So I decided to:
1. Separate each word from the link
2. Encode it
3. Concatenate the new encoded words, for example:
3.A. APPLE (APPLE)
3.B. %E3%81%AF%E3%81%AF%E3%81%AF.pdf (ははは.pdf)
with the (space) converted to %20, now becomes APPLE%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf
Here's my code:
public static String[] splitWords(String sentence) {
String[] words = sentence.split(" ");
return words;
}
The calling code:
String urlLastPath = getLastPathFromUrl(pdfUrl);
String[] splitWords = splitWords(urlLastPath);
for (String word : splitWords) {
String urlEncoded = URLEncoder.encode(word, "utf-8"); //STUCKED HERE
}
I now want to concatenate each unicoded string(urlEncoded) inside the indices to finally form like APPLE%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf. How do I do this?
actually the %20 is encoded as %2520 so just call URLEncoder.encode(word, "utf-8"); so you will get result like this APPLE+%E3%81%AF%E3%81%AF%E3%81%AF.pdf and in final result replace + with %20.
Do you want to do something like this:
// Get the whole url as string
Stirng urlString = pdfUrl.toString();
// get the string before the last path segment
String result = urlString.substring(0, urlString.lastIndexOf("/"));
String urlLastPath = getLastPathFromUrl(pdfUrl);
String[] splitWords = splitWords(urlLastPath);
for (String word : splitWords) {
String urlEncoded = URLEncoder.encode(word, "utf-8");
// add the encoded part to the url
result += urlEncoded;
}
Now the string result is your encoded URL as a string.
Possibly easy with org.apache.commons.io.FilenameUtils.
Split your url into baseUrl and the file name and extension.
Encode the file name and extension
Join them together
String url = "http://xxx.xx.xx.xx/resources/upload/pdf/APPLE ははは.pdf";
String baseUrl = FilenameUtils.getPath(url); // GIVES: http://xxx.xx.xx.xx/resources/upload/pdf/
String myFile = FilenameUtils.getBaseName(url)
+ "." + FilenameUtils.getExtension(url); // GIVES: APPLE ははは.pdf
String encoded = URLEncoder.encode(myFile, "UTF-8"); //GIVES: APPLE+%E3%81%AF%E3%81%AF%E3%81%AF.pdf
System.out.println(baseUrl + encoded);
Output:
http://xxx.xx.xx.xx/resources/upload/pdf/APPLE+%E3%81%AF%E3%81%AF%E3%81%AF.pdf
Don't reinvent the wheel. Use URLEncoder for encoding the URL.
URLEncoder.encode(yourArgumentsHere, "utf-8");
Moreover, where do you get your URL from, so that you have to split it before encoding? You should first build the arguments (last part), then just append it onto the base URL.

How to split the string a android?

I am working on android application. I am getting the image from gallery. Also I am getting the image path from gallery. Now my requirement is I want to get only the image name with the extension . How can I do that? Please help me.
String imgpath = "/mnt/sdcard/joke.png";
The image extension can be anything joke.png or joke.jpeg. I need to get the image name with extension finally.
i.e I want to split the above string and get only joke.png.
How can I achieve that? Please help me in this regard.
String imgpath = "/mnt/sdcard/joke.png";
String result = imgpath.substring(imgpath.lastIndexOf("/") + 1);
System.out.println("Image name " + result);
Output :-
Image name joke.png
You should read How do I get the file name from a String containing the Absolute file path?
You can do that in Android like in any Java program:
String[] parts = imagepath.split("/");
String result = parts[parts.length-1];
String s[] = imgpath.split("/");
String result = s[s.length-1];
String imgName = imgpath.substring((imgpath.lastIndexOf("/") + 1), imgpath.length());
You can get this with Regex too, if that is the hammer you have in your hands:
String fileName = null;
Pattern pattern = Pattern.compile("(^|.*/)([^/]*)$");
Matcher m = pattern.getMatcher(filenameWithPath);
if(matcher.matches()) {
fileName = matcher.group(2);
}
But don't be tempted to do this. This is less readable, and probably even slower than the other methods.

Java: String manipulation. Fetch last subpath in a URL

Lets say I have a URL http://example.com/files/public_files/test.zip and I want to extract the last subpath so test.zip, How would I be able do this?
I am from Python so I am still new to Java and learning. In Python you could do something like this:
>>> x = "http://example.com/files/public_files/test.zip"
>>> x.split("/")[-1]
'test.zip'
There are many ways. I prefer:
String url = "http://example.com/files/public_files/test.zip";
String fileName = url.substring(url.lastIndexOf("/") + 1);
Using String class method is a way to go. But given that you are having a URL, you can use java.net.URL.getFile():
String url = "http://example.com/files/public_files/test.zip";
String filePart = new URL(url).getFile();
The above code will get you complete path. To get the file name, you can make use of Apache Commons - FilenameUtils.getName():
String url = "http://example.com/files/public_files/test.zip";
String fileName = FilenameUtils.getName(url);
Well, if you don't want to refer to 3rd party library for this task, String class is still an option to go for. I've just given another way.
you can use the following:
String url = "http://example.com/files/public_files/test.zip";
String arr[] = url.split("/");
String name = arr[arr.length - 1];
Most similar to the python syntax is :
String url = "http://example.com/files/public_files/test.zip";
String [] tokens = url.split("/");
String file = tokens[tokens.length-1];
Java lacks the convenient [-n] nth to last selector that Python has. If you wanted to do it all in one line, you'd have to do something gross like this:
String file = url.split("/")[url.split("/").length-1];
I don't recommend the latter

Categories

Resources