Java, get full path of file and removing filename - java

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\

Related

Telling .jar file to make a file on the Desktop instead of within itself (java) mac

I have a program which includes the following line of code:
//String s = fileName;
File location = new File(s);
and then I have
//String contents = whatIWantToPrint;
OutputStream print = new FileOutputStream(location);
print.write(contents.getBytes());
print.close();
telling the program to print the string contents to the file s. However the file appears within the folder that the program is in rather than the directory in which the program is in. For example if the program is on the persons desktop I want it to make the file on their desktop.
I used the following line in terminal to make the program a jar file (mac):
jar -cvmf manifest.txt Generate.jar *.class
Someone told me to do this:
String dir = System.getProperty("home.dir"+"/Desktop");
String filePath = dir + File.separator + ss + ".txt";
File location = new File(filePath);
But I'm not sure if that's what will make the program make the file in the desktop and it also throws a security exception so it doesn't work anyways
You should do:
String s= System.getProperty("user.home");
and append path separator and file name
String filePath = s + File.separator + "desktop" + File.separator + "myFile.txt";
You could try this
String DEFAULT_USER_DIR = System
.getProperty("user.home"+"/Desktop");
File location = new File(DEFAULT_USER_DIR);
user.dir returns User's current working directory
See the javadoc here.

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

Invalid character in zipfile path (Windows)

I have to unzip one file that contains a invalid path for Windows OS:
9f96bc3dE8d94fc2B1fd2ff9ed8d2637\html\portlet\facilit\planooperativo\themes\plano-operativo-theme\css\data:image
data:image, in windows it's not permited to be directory with : in path
then my code to unzip got this exception
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
How can I fix it, changing : for another character (underline for example) or just skip this directory.
I've tried this code below, but it doesn't work:
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
String nameFile = newFile.getAbsolutePath();
if (nameFile.contains(":")){
nameFile.replaceAll(":", "_");
newFile = new File(nameFile);
}
actually my path needs to contain : because the complete path needs to begin with C:\, please give me one solution (Detail: it works fine in Mac)
while (ze != null) {
String fileName = ze.getName();
if (fileName.contains(":")){
fileName = fileName.replaceAll(":", "_");
}

Get file size in Java from relative path to file

How can I get file size in Java if I have a relative path to a file such as:
String s = "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with two diferent strings:
String[] separatedPath = s.split("/");
List<String> wordList = Arrays.asList(separatedPath);
String ret = "/" + wordList.get(1) + "/" + wordList.get(2) + "/" + wordList.get(3)+ "/" + wordList.get(4);
s = ret;
In this case s="/documents/19/21704/file2.pdf";
In second case s="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with:
File file1 = new File(s);
long filesize = file1.length();
and with:
String filePath = new File(s).toURI().getPath();
File file2 = new File(filePath);
long filesize2 = file1.length();
and also with (if the problem is in not providing full path):
String absolutePath = FileUtil.getAbsolutePath(file1);
File file3 = new File(absolutePath);
long filesize3 = file3.length();
byte[] bytes1=FileUtil.getBytes(file1);
byte[] bytes2=FileUtil.getBytes(file2);
byte[] bytes3=FileUtil.getBytes(file3);
I am always getting in debug that filesizes in all cases are 0.
Maybe is worth noticing that the three attributes of file1 and file2 and file3 are always:
filePath: which is always null;
path: "/documents/19/21704/liferay-portlet-development.pdf"
prefixLength: 1
Since I am also using Liferay I also tried their utility.
long compId = article.getCompanyId();
long contentLength = DLStoreUtil.getFileSize(compId, CompanyConstants.SYSTEM, s);
I also should notice that in my .xhtml view I can access the file with:
<a target="_blank"
href="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc">
file2.pdf
</a>
Pdf opens in a new window. So it is stored on my server.
What am I doing wrong here? That I cant get the file size from bean?
Any answer would be greatly appreciated.
What am I doing wrong here?
In Java, you can use the File.length() method to get the file size in bytes.
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double bytes = file.length();
}
System.out.println("bytes : " + bytes);
The problem is that your "relative" path is expressed as an absolute path (begining with "/", which is read as FS root).
A relative file path should look like:
documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
./documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
Or, you could get your application root folder File and compose the absolute path:
File rootFolder =new File("path to your app root folder");
File myfile=new File(rootFolder, "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc");

How to get FolderName and FileName from the DirectoryPath

I have DirectoryPath:
data/data/in.com.jotSmart/app_custom/folderName/FileName
which is stored as a String in ArrayList
Like
ArrayList<String> a;
a.add("data/data/in.com.jotSmart/app_custom/page01/Note01.png");
Now from this path I want to get page01 as a separate string and Note01 as a separate string and stored it into two string variables. I tried a lot, but I am not able to get the result. If anyone knows help me to solve this out.
f.getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
For example
File f = new File("/home/jigar/Desktop/1.txt");
System.out.println(f.getParent());// /home/jigar/Desktop
System.out.println(f.getName()); //1.txt
Update: (based on update in question)
if data/data/in.com.jotSmart/app_custom/page01/Note01.png is valid representation of file in your file system then
for(String fileNameStr: filesList){
File file = new File(fileNameStr);
String dir = file.getParent().substring(file.getParent().lastIndexOf(File.separator) + 1);//page01
String fileName = f.getName();
if(fileName.indexOf(".")!=-1){
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}
}
For folder name: file.getParentFile().getName().
For file name: file.getName().
create a file with this path...
then use these two methods to get directory name and file name.
file.getParent(); // dir name from starting till end like data/data....../page01
file.getName(); // file name like note01.png
if you need directory name as page01, you can get a substring of path u got from getparent.
How about using the .split ?
answer = str.split(delimiter);

Categories

Resources