How to Check filename - java

I have a method that reads filename for a file from a certain source. My method should handle two types of files. My next method depends on the name of the file.
_InPayed.txt" "_OutPayed.txt
My problem is how to check if the filename is ..._inpayed Or ..._OutPayed
How to check the string after the strick " _"
Code:
public class FilenameDemo {
public static void main(String[] args) {
final String FPATH = "/home/mem/"filename.txt";
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
}
}

No need for subString. A simple call to contains(...) is all you need. More importantly, learn to use the API.
if (myString.toLowerCase().contains("inpayed")) {
// do something
}
String API

If you want to check the certain string in the file name then use contains method.
&
You can get the file name after _ using below expression
System.out.println("Filename = "+FPATH.substring(FPATH.lastIndexOf("_")+1,FPATH.lastIndexOf(".")));

The string must contain one and only one _ for this to work.
String fullFile="whatever_InOutPayed.txt"
String[] split = file.split("_");
// split[0] = "whatever"
// split[1] = "InOutPayed.txt"
String file = split[1];
If it contains more than one then take the last element of the array
String file = split[split.length - 1];
or you can easily use String.contains().

You can use substring() method to extract a desired part of a file name stored as String. Or if the part you are checking will always be at the end of the String a simpler option is to use endsWith(). Check the documentation for details about the method usage.

Related

Cleaning a file name in Java

I want to write a script that will clean my .mp3 files.
I was able to write a few line that change the name but I want to write an automatic script that will erase all the undesired characters $%_!?7 and etc. while changing the name in the next format Artist space dash Song.
File file = new File("C://Users//nikita//Desktop//$%#Artis8t_-_35&Son5g.mp3");
String Original = file.toString();
String New = "Code to change 'Original' to 'Artist - Song'";
File file2 = new File("C://Users//nikita//Desktop//" + New + ".mp3");
file.renameTo(file2);
I feel like I should make a list with all possible characters and then run the String through this list and erase all of the listed characters but I am not sure how to do it.
String test = "$%$#Arti56st_-_54^So65ng.mp3";
Edit 1:
When I try using the method remove, it still doesn't change the name.
String test = "$%$#Arti56st_-_54^So65ng.mp3";
System.out.println("Original: " + test);
test.replace( "[0-9]%#&\\$", "");
System.out.println("New: " + test);
The code above returns the following output
Original: $%$#Arti56st_-_54^So65ng.mp3
New: $%$#Arti56st_-_54^So65ng.mp3
I'd suggest something like this:
public static String santizeFilename(String original){
Pattern p = Pattern.compile("(.*)-(.*)\\.mp3");
Matcher m = p.matcher(original);
if (m.matches()){
String artist = m.group(1).replaceAll("[^a-zA-Z ]", "");
String song = m.group(2).replaceAll("[^a-zA-Z ]", "");
return String.format("%s - %s", artist, song);
}
else {
throw new IllegalArgumentException("Failed to match filename : "+original);
}
}
(Edit - changed whitelist regex to exclude digits and underscores)
Two points in particular - when sanitizing strings, it's a good idea to whitelist permitted characters, rather than blacklisting the ones you want to exclude, so you won't be surprised by edge cases later. (You may want a less restrictive whitelist than I've used here, but it's easy to vary)
It's also a good idea to handle the case that the filename doesn't match the expected pattern. If your code comes across something other than an MP3, how would you like it to respond? Here I've through an exception, so the calling code can catch and handle that appropriately.
String new = original.replace( "[0-9]%#&\\$", "")
this should replace almost all the characters you don't want
or you can come up with your own regex
https://docs.oracle.com/javase/tutorial/essential/regex/

How to remove a substring in java

I am receiving a file path with "xyz" appended to it. name would look like D:/sdcard/filename.docxyz
i am using the below code to remove xyz but it is not working. what is missing here ?
String fileExtension = path.substring(path.lastIndexOf(".")+1);
String newExtension= fileExtension;
newExtension.replace("xyz", "");
path.replace(fileExtension, newExtension);
return path;
What is missing is that you need to save the result of your operations. Strings are immutable in Java, and the results of all String manipulations are therefore returned in the form of a new String:
newExtension = newExtension.replace("xyz", "");
path = path.replace(fileExtension, newExtension);
String in java are immutable, and changes upon it never occurs in place, but every time a new string is returned,
newExtension = newExtension.replace("xyz", "");
You could also use replaceAll() with a regex.
public static void main(String[] args) {
String s = "D:/sdcard/filename.docxyz";
System.out.println(s.replaceAll("xyz$", "")); // $ checks only the end
}
O/P :
input : s = "D:/sdcard/filename.docxyz";
D:/sdcard/filename.doc
input : String s = "D:/sdcard/filenamexyz.docxyz";
output : D:/sdcard/filenamexyz.doc
newExtension.replace("xyz", "");
Will only return string which has "xyz" removed but newExtension will remain as it is. Simple fix for your problem is use as below
String newExtension= fileExtension.replace("xyz", "");

How to get the string before .(dot) and after /(last) slash in Java

I have a string like this:
"core/pages/viewemployee.jsff"
From this code, I need to get "viewemployee". How do I get this using Java?
Suppose that you have that string saved in a variable named myString.
String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));
But you need to make the same control before doing substring in this one, because if there aren't those characters you will get a "-1" from lastIndexOf(), or indexOf(), and it will break your substring invocation.
I suggest looking for the Javadoc documentation.
You can solve this with regex (given you only need a group of word characters between the last "/" and "."):
String str="core/pages/viewemployee.jsff";
str=str.replaceFirst(".*/(\\w+).*","$1");
System.out.println(str); //prints viewemployee
You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.
String myStr = "core/pages/viewemployee.bak.jsff";
String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");
String fileNameStr = "";
for(int i = 0; i < fileNameTokens.length - 1; i++) {
fileNameStr += fileNameTokens[i] + ".";
}
fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);
System.out.print(fileNameStr) //--> "viewemployee.bak"
These are file paths. Consider using File.getName(), especially if you already have the File object:
File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"
And to remove the extension:
String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"
With this we can handle strings like "../viewemployee.2.jsff".
The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..
The below will get you viewemployee.jsff:
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn = idx >= 0 ? fileName.substring(idx + 1) : fileName;
To remove the file Extension and get only viewemployee, similarly:
idx = fileNameWithExtn.lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn;

Using regular expressions to rename a string

In java, I want to rename a String so it always ends with ".mp4"
Suppose we have an encoded link, looking as follows:
String link = www.somehost.com/linkthatIneed.mp4?e=13974etc...
So, how do I rename the link String so it always ends with ".mp4"?
link = www.somehost.com/linkthatIneed.mp4 <--- that's what I need the final String to be.
Just get the string until the .mp4 part using the following regex:
^(.*\.mp4)
and the first captured group is what you want.
Demo: http://regex101.com/r/zQ6tO5
Another way to do this would be to split the string with ".mp4" as a split char and then add it again :)
Something like :
String splitChar = ".mp4";
String link = "www.somehost.com/linkthatIneed.mp4?e=13974etcrezkhjk"
String finalStr = link.split(splitChar)[0] + splitChar;
easy to do ^^
PS: I prefer to pass by regex but it ask for more knowledge about regex ^^
Well you can also do this:
Match the string with the below regex
\?.*
and replace it with empty string.
Demo: http://regex101.com/r/iV1cZ8
Try below code,
private String trimStringAfterOccurance(String link, String occuranceString) {
Integer occuranceIndex = link.indexOf(occuranceString);
String trimmedString = (String) link.subSequence(0, occuranceIndex + occuranceString.length() );
System.out.println(trimmedString);
return trimmedString;
}

Java: getting parameters from a URI who contains a file

let's say I have a file located in:
http://example.com/123.app
now I get the file name using the following (u is an entire url string):
String fileName = u.substring( u.lastIndexOf('/')+1, u.length() );
but I want to put on the same file name also parameters, so it'll look like, this:
http://example.com/123.app?id=87983
And I want to have a String fileName which will contain '123.app', and also String id which will contain '87983' and possibly more parameters.
How would I go about achieving this?
Firstly, take a look at this post, which uses the URL class to make working with the different parts of the URL string a lot easier.
Could you share a link to an URL parsing implementation?
Secondly, you would need to take the Query part of the URL and the Path part of the URL and substring the returned values to get the information that you desire. It should be pretty straight forward.
Use the API of URI! That's what it's for. Forget all this substring/regex/spit stuff.
you need to use the split method on string. So for example on your fileName string
String[] mystrings = fileName.split("?");
then mystrings[0] is your filename and mystrings[1] is your parameter
A simple way is : just repeat substring :
int qidx = filename.indexOf("?");
String realFilename = filename.substring(0, qidx);
String parameters = filename.substring(qidx+1);
and so on for parsing parameters.
If you are writing a servlet try :
String fileName = request.getServletPath();
and for the parameters somthing like
String id = request.getParameter("id");
Try this regex:
String s = "http://example.com/123.app?id=87983";
String[] split = s.split(".*/|\\?id=");
String filename = split[1];
String id = (split.length == 3) ? split[2] : null;

Categories

Resources