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('.'));
Related
I have several paths to read into the program from txt format file. In order to simply the process, I would like to stored all the paths/directory into one txt file and assign values to each path.
TXT file:
C:/folder1/data
D:/folder2/excel
E:/folder3/doc
JAVA:
final String Local_dir = System.getenv().get("USERNAME")
String dir = FileUtils.readFileToString(new File("C:/Users/$Local_dir/Desktop/sample_paths.txt"), "UTF-8")
final String Path1 = dir.trim()
final String Path2 = dir.trim()
final String Path3 = dir.trim()
My question is how can I update the above code to make it work?
You can get the home directory from your computer and use the Files.readAllLines method to get the whole content:
String user = System.getProperty("user.home");
List<String> lines = Files.readAllLines(Paths.get(user, "Desktop", "sample_paths.txt"));
String path1 = lines.get(0);
String path2 = lines.get(1);
String path3 = lines.get(2);
Assuming that your file has carriage return and line feeds, and that your text file does not contain this first line TXT file:, I would suggest the following code:
final String Local_dir = System.getenv().get("USERNAME")
String dir = FileUtils.readFileToString(new File("C:/Users/$Local_dir/Desktop/sample_paths.txt"), "UTF-8");
String[] lines = dir.split("\r\n");
final String Path1 = lines[0];
final String Path2 = lines[1];
final String Path3 = lines[2];
So it is a simple splitting to create the lines.
Edit: I also assume that your two first lines of code working for you.
I have a CSV file and I want to extract part of the file name using Java code.
For example if the name of the file is --> StudentInfo_Mike_Brown_Log.csv
I want to be able to just extract what is between the first two _'s in the file name. Therefore in this case I would be extracting Mike
So far I am doing the following:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
String extractedInfo= fileName.substring(fileName.indexOf("_"), fileName.indexOf("."));
System.out.println(extractedInfo);
This code currently gives me _Mike_Brown_brown_Log but I want to only print out Mike.
You can use split with a Regex to split the String into substrings.
Here is an example:
final String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
final String[] split = fileName.split("_");
System.out.println(split[1]);
Try this:
int indexOfFirstUnderscore = fileName.indexOf("_");
int indexOfSecondUnderscore = fileName.indexOf("_", indexOfFirstUnderscore+2 );
String extractedInfo= fileName.substring(indexOfFirstUnderscore+1 , indexOfSecondUnderscore );
System.out.println(extractedInfo);
You could use the getName() method from the File object to return just the name of the file (with extension but without trailing path) and than do a split("_") like #Chasmo mentioned.
E.g.
File input = new File(file);
String fileName = input.getName();
String[] partsOfName = fileName.split("_");
System.out.println(Arrays.toString(partsOfName));
You can use lastIndexOf(), in addition to indexOf():
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
filename = file.getName();
String extractedInfo= fileName.substring(
fileName.indexOf("_"),
fileName.lastIndexOf("_"));
System.out.println(extractedInfo);
It is important to firstly call file.getName() so this method does not get confused with underscore '_' characters in the file path.
Hope this helps.
Use indexOf and substring method of String class:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
int indexOfUnderScore = fileName.indexOf("_");
int indexOfSecondUnderScore = fileName.indexOf("_",
indexOfUnderScore + 1);
if (indexOfUnderScore < 0 || indexOfSecondUnderScore < 0) {
throw new IllegalArgumentException(
"string is not of the form string1_string2_ " + fileName);
}
System.out.println(fileName.substring(indexOfUnderScore + 1,
indexOfSecondUnderScore));
Solved from the previous answer:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
fileName = file.getName();
System.out.println(fileName.split("\\.")[0]);
I have a requirement that i have to split a String that have .xls or .xlsx extention. I have to upload the file from local and save it in a directory in my project.i am able to do it. Now the requirement is that i have to check if that file which is uploaded if duplicate i will change the name of the file and that append the extention to that.So that i multiple client access the file and try to upload each file with a different name should save into the folder.So i am doing this to split the Sring but i dont want this approach.
public class RenameFile {
public static void main(String[] args) {
String str = new String("Udemy.txt");
String result[] = str.split("\\.");
for (String ff : result) {
System.out.println(ff);
}
}
}
i dont a loop for manipulating my String.i want something that will just cut the fileName and ext and i can store it somewhere and then after opeartion i also can append them.plese help ..
The file extension is the part after the last dot and therefore the following should work
String str = "Udemy.txt";
String fileName = str.substring(0, str.lastIndexOf("."));
String extension = str.substring(str.lastIndexOf(".") + 1);
Try this,
String fileName = "MyFile.xls";
int dotIndex = fileName.lastIndexOf(".");
String name = fileName.substring(0, dotIndex); // MyFile
String extension = fileName.substring(dotIndex); // .xls
// then you can change and re-construct the file name
you can use like that,
String result[] = str.split(".");
String fileName = result[0];
String extension = result[1];
String str = "Udemy.txt";
int ix = str.lastIndexOf('.');
if (ix >= 0) {
String ext = str.substring(ix);
String root = str.substring(0, ix);
...
}
I am trying to get a path of an image in my android device, such as:
/ storage/emulated/0/DCIM/Camera/NAME.jpg
and just trying to grab the image name, but i can.
I am trying with ...
String s = imagePath;
Where the route imagePath
s = s.substring (s.indexOf ("/") + 1);
s.substring s = (0, s.indexOf () ".");
Log.e ("image name", s);
it returns me :
storage/emulated/0/DCIM/Camera/NAME.jpg
and i only want
NAME.jpg
You need String.lastIndexOf():
String imagePath = "/path/to/file/here/file.jpg";
String path = imagePath.substring(imagePath.lastIndexOf('/') + 1);
You can do something like that:
File imgFile = new File(imagePath);
String filename = imgFile.getFilename();
This saves you a lot of hassle when you want to use your application cross-platform, because on Linux you have "/" as path delimiters and "\" on Windows
In case, if you are dealing with File object, then you can use its predefined method getName().
i.e.:
File mFile = new File("path of file");
String filename = mFile.getName();
Let's say I have the following string
http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png
What would be the best way to extract b84.png from it? My program will be getting a list of image URLs and I want to extract the file name with its extension from each URL.
I would recommend using URI to create a File like this:
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
URI uri = URI.create(url);
File f = new File(uri.getPath());
The uri.getPath() returns only the path portion of the url (i.e. removes the scheme, host, etc.) and produces this:
/photos/images/original/000/748/132/b84.png
You can then use the created File object to extract the file name from the full path:
String fileName = f.getName();
System.out.println(fileName);
Output of print statement would be:
b84.png
However if you are not at all concerned by the input format of the url(s) then the substring answers are more terse. I figured I would offer an alternative. Hope it helps.
Try,
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String fileName = url.subString(url.lastIndexOf("/")+1);
String[] urlArray=yourUrlString.split("/");
String fileName=urlArray[urlArray.length-1];
I think, string lastIndexOf method is the best way to extract file name
String str = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String result = str.substring(str.lastIndexOf('/')+1,str.length());
The method perfect for you
public String Name(String url){
url=url.replace('\\', '/');
return url.substring(url.lastIndexOf('/')+1,url.length());
}
this method returns any filename of any directory...whitout errors because convert the "\" to "/" so never will have problems with diferent directories
You can try this-
String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png"
url = url.substring(url.lastIndexOf("."));
If you don't png instead of .png, just change the last line to this-
url = url.substring(url.lastIndexOf(".") + 1);