Getting the right slash for each platform - java

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

Related

save file with different name in spring boot

I am uploading one file that is kind of multipart. I want this file to save with different name.
tried with renameTo method but did not work.
tried moveto but did not work
below is my code
here graphic is multipart file
String picName = graphic.getOriginalFilename();EN_LENGTH) + "." + graphic.getContentType();
Path dirLocation = Paths.get(dirPath);
String newName = CommonUtil.getToken(Constants.STANDRAD_TOKEN_LENGTH) + "." + graphic.getContentType();
try {
InputStream is = graphic.getInputStream();
Files.copy(is, dirLocation.resolve(picName), StandardCopyOption.REPLACE_EXISTING);
boolean a = new File(dirLocation+picName).renameTo(new File(dirLocation+newName));
for security reasons I want it to save with different name.
Solved the issue by correcting the filename. The file name which I was generating randomly was not correct. it had some slash etc.

Java, get full path of file and removing filename

I'm trying to get the directory path to a file. The issue I am having is getting the last \ or / of the directory. As this code is supposed to work on all operating systems, I can't seem to find any solution for this. Any help is appreciated.
My code so far:
System.out.print("Enter dir: ");
String path = kb.nextLine();
File pathes = new File(path);
String path2 = pathes.getParent();
path = path.substring(0, path.lastIndexOf("\\")+1);
System.out.println("PATH: " + path);
System.out.println("PATH2: "+path2);
My output is:
PATH: C:\Users\User\Desktop\test\
PATH2: C:\Users\User\Desktop\test
This is just test code and not the real code I'm working on.
EDIT
What I'm trying to get is
C:\Users\User\Desktop\test\
from
C:\Users\User\Desktop\test\test.txt
To get the absolute path to the parent directory you can do:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt");
String path = f.getParentFile().getAbsolutePath();
System.out.println(path);
Output:
C:\Users\User\Desktop\test
If you really want the trailing slash, then you can just append File.separator:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt ");
String path = f.getParentFile().getAbsolutePath() + File.separator;
System.out.println(path);
Output:
C:\Users\User\Desktop\test\

Get character from string between similar sings

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

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

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