Get character from string between similar sings - java

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();

Related

java.io.File constructor behaviour or perhaps multithreading issue?

I have the following code:
class Abcd{
//wired by spring to give the directory filePath ="/var/tmp/"
private String filePath;
public void myMethod(String id, String date){
filePath= filePath+ id+ "_" + date;
File f = new File(filePath);
if(f.exists){//Do something}
else{
System.out.println("File not found at file path:"+filePath);
}
}
}
The above code is behaving weird , intermittently the filePath contains all the files of directory /var/tmp/ . So , if /var/tmp directory contains two files called "id1_01012017" and "id2_10102017".
This is the intermittent output
File not found at file path:/var/tmp/id1_01012017id2_10102017
Am unable to figure out whats happening
The best way to do this is to maintain that filePath remains immutable. You will find that if you change this line:
filePath = filePath + id + "_" + date;
to the following:
String tempFilePath = filePath + id + "_" + date;
and operate on tempFilePath instead of filePath, your code will become thread-safe and work as expected.

How to extract part of file name of a CSV file in Java

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]);

Remove filename from a URL/Path in java

How do I remove the file name from a URL or String?
String os = System.getProperty("os.name").toLowerCase();
String nativeDir = Game.class.getProtectionDomain().getCodeSource().getLocation().getFile().toString();
//Remove the <name>.jar from the string
if(nativeDir.endsWith(".jar"))
nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf("/"));
//Load the right native files
for(File f : (new File(nativeDir + File.separator + "lib" + File.separator + "native")).listFiles()){
if(f.isDirectory() && os.contains(f.getName().toLowerCase())){
System.setProperty("org.lwjgl.librarypath", f.getAbsolutePath()); break;
}
}
That's what I have right now, and it work. From what I know, because I use "/" it will only work for windows. I want to make it platform independent
Consider using org.apache.commons.io.FilenameUtils
You can extract the base path, file name, extensions etc with any flavor of file separator:
String url = "C:\\windows\\system32\\cmd.exe";
String baseUrl = FilenameUtils.getPath(url);
String myFile = FilenameUtils.getBaseName(url)
+ "." + FilenameUtils.getExtension(url);
System.out.println(baseUrl);
System.out.println(myFile);
Gives,
windows\system32\
cmd.exe
With url; String url = "C:/windows/system32/cmd.exe";
It would give;
windows/system32/
cmd.exe
By utilizing java.nio.file; (afaik introduced after J2SE 1.7) this simply solved my problem:
Path path = Paths.get(fileNameWithFullPath);
String directory = path.getParent().toString();
You are using File.separator in another line. Why not using it also for your lastIndexOf()?
nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf(File.separator));
File file = new File(path);
String pathWithoutFileName = file.getParent();
where path could be "C:\Users\userName\Desktop\file.txt"
The standard library can handle this as of Java 7
Path pathOnly;
if (file.getNameCount() > 0) {
pathOnly = file.subpath(0, file.getNameCount() - 1);
} else {
pathOnly = file;
}
fileFunction.accept(pathOnly, file.getFileName());
Kotlin solution:
val file = File( "/folder1/folder2/folder3/readme.txt")
val pathOnly = file.absolutePath.substringBeforeLast( File.separator )
println( pathOnly )
produces this result:
/folder1/folder2/folder3
Instead of "/", use File.separator. It is either / or \, depending on the platform. If this is not solving your issue, then use FileSystem.getSeparator(): you can pass different filesystems, instead of the default.
I solve this problem using regex.
For windows:
String path = "";
String filename = "d:\\folder1\\subfolder11\\file.ext";
String regEx4Win = "\\\\(?=[^\\\\]+$)";
String[] tokens = filename.split(regEx4Win);
if (tokens.length > 0)
path = tokens[0]; // path -> d:\folder1\subfolder11
Please try below code:
file.getPath().replace(file.getName(), "");

Getting the right slash for each platform

I have a JFilechooser to select a filename and path to store some data. But I also want to store an additional file in the same path, same name but different extension. So:
File file = filechooser.getSelectedFile();
String path = file.getParent();
String filename1 = file.getName();
// Check the extension .ext1 has been added, else add it
if(!filename1.endswith(".ext1")){
filename2 = filename1 + ".ext2";
filename1 += ".ext1";
}
else{
filename2 = filename1;
filename2 = filename2.substring(0, filename2.length-4) + "ext2";
}
// And now, if I want the full path for these files:
System.out.println(path); // E.g. prints "/home/test" withtout the ending slash
System.out.println(path + filename1); // E.g. prints "/home/testfilename1.ext1"
Of course I could add the "/" in the middle of the two strings, but I want it to be platform independent, and in Windows it should be "\" (even if a Windows path file C:\users\test/filename1.ext1 would probably work).
I can think of many dirty ways of doing this which would make the python developer I'm carrying inside cry, but which one would be the most clean and fancy one?
You can use the constants in the File class:
File.separator // e.g. / or \
File.pathSeparator // e.g. : or ;
or for your path + filename1 you can do
File file = new File(path, filename1);
System.out.println(file);
Just use the File class:
System.out.println(new File(file.getParent(), "filename1"));
You can use:
System.getProperty("file.separator");

Create a File in a folder

In Java, I have a File object representing a folder:
String folderName = "/home/vektor/folder";
File folder = new File(folderName);
Now I want to create another File representing a file in this folder. I want to avoid doing a string concatenation like this:
String fileName = "test.txt";
File file = new File(folderName + "/" + fileName);
Because if I go deeper in creating this structure, I will come up with something like this:
File deepFile = new File(folderName + "/" + anotherFolderName + ... + "/" + fileName);
I would instead like to do something like
File betterFile = folder.createUnder(fileName);
Or even:
File otherFile = SomeFileUtils.createFileInFolder(folder, fileName);
Do you know of such solution?
Note: It's quite OK to use "/" because Java will translate it to "\" for Windows, but it is not clean - I should use something like "file.separator" from System.getProperties().
Look at the Javadoc for File and you will see that the constructor takes a File object as parent.
Use the following form:
File deepFile = new File(folder, fileName);
I would use
String folderName =
String fileName =
File under = new File(folderName, fileName);
or
File folderFile =
String fileName =
File under = new File(folderFile, fileName);
simple as that ;)

Categories

Resources