Get absolute path in Java - java

I have string:
String s = "~/abc/d.png"
How can I get absolute path of this file?
I've tried:
File file = new File(s);
String absolutePath = file.getAbsolutePath();
But it can't reslove ~ symbol.

Java isn't going to know what the ~ means since it's a shell expansion for your home directory. You can do this before handing it off to File:
s = s.replace("~",System.getProperty("user.home"));

Related

Inputstream is null, while loading a file from a file path in windows service

Im trying to read a file from a path.
This is my sample code;
String path = "repository"+ File.separator +"resources"+ File.separator +"api_templates";
String fileName = path + TEMPLATE_FILE_PREFIX + type + ".xml";
InputStream in = null;
try {
log.info("##############File path#############"+fileName);
in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
Here i get inputstream as null. I suspect the system could not load the file. But when i print my filepath, it correctly prints my file path.
This problem occurs only when i try to run my server as windows service, using "yajsw".
What might be the issue?
Edit:
My Sample wrapper-conf file;
#********************************************************************
# working directory
#********************************************************************
wrapper.working.dir=${my_home}
............
wrapper.java.additional.2 = -Xms256m
wrapper.java.additional.3 = -Xmx1024m
wrapper.java.additional.4 = -XX:MaxPermSize=256m
wrapper.java.additional.5 = -XX:+HeapDumpOnOutOfMemoryError
wrapper.java.additional.6 = -XX:HeapDumpPath=${my_home}\\repository\\logs\\heap-dump.hprof
wrapper.java.additional.7 = -Djava.endorsed.dirs=${my_home}\\lib\\endorsed;${java_home}\\jre\\lib\\endorsed
This is because of a classpath issue between resources and files. We can not use classloaders to access files. For that we need to use File, filereader, file input stream. After changing like this everything works fine;
InputStream in = new FileInputStream(filePath);

How to access folder near to my application in webapp?

my application is under wtpwebapps folder
wtpwebapps->myapp
and my files are under the wtpwebapps->files folder
wtpwebapps->files->file1
wtpwebapps->files->file2
wtpwebapps->files->file3
i've tried
request.getSession().getServletContext().getRealPath();
and got this path
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
when i append
"\files\file1"
to the path and acces that files then it gives me error that
The requested resource is not available
How to resolve this issue?
Try this:
File currentDir=new File(request.getSession().getServletContext().getRealPath())
// or try this instead too:
// File currentDir=new File(".");
File myFile=new File(currentDir,"files\\file1");
You can get the absolute path to your myApp/WEB-INF/classes directory as below:
URL resource = getClass().getResource("/");
String path = resource.getPath();
Now you can manipulate the path string to go to your files:
path = path.replace("your_app_name/WEB-INF/classes/", "");
path = path + "files/file1";
Here path is now referring to file1 present in wtpwebapps->files.
If you append literally \files\file1 this won´t work because backslash is the escape character. Try
/files/file1
Java will convert to the platform path seperator.
Here is the code from a listener ....
System.out.println("Inside contextInitialized()");
System.out.println( servletContextEvent.getServletContext().getRealPath("") );
System.out.println( servletContextEvent.getServletContext().getRealPath("/") );
String filePath = servletContextEvent.getServletContext().getRealPath("/public/file.txt");
File file = new File(filePath);
System.out.println( filePath );
System.out.println( file.exists() );
and its output...
Inside contextInitialized()
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp\
C:\...\WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SampleWebApp\public\file.txt
true
Note that i have edited the path in between.

How to get absolute path of file depends on windows 32-bit or 64-bit machine

I am trying to get absolute file path on java, when i use the following code :
File f = new File("..\\webapps\\demoproject\\files\\demo.pdf")
String absolutePath = f.getAbsolutePath();
It gives the correct file path on 32-bit machine as
C:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
But when i run the same on 64-bit machine it gives FileNotFound Exception (because of Program Files(x86)), How to get correct path regardless of OS bit. Could anybody please help.
I have used below code and it is giving correct file path where i have used
System.getProperty("user.dir") to get the current working directory and System.getenv("ProgramFiles") to check program files name.
`
String downloadDir = "..\\webapps\\demoproject\\files";
String currentdir = System.getProperty("user.dir");
String programFiles = System.getenv("ProgramFiles");
String filePath = "";
if(programFiles.equals("C:\\Program Files"))
{
filePath = currentdir + "\\" + downloadDir + "\\demo.pdf";
}
else
{
filePath = currentdir + "\\" + "bin"+ "\\" + downloadDir + "demo.pdf";
}
File pdfFile = new File(filePath);
String absolutePath = pdfFile.getAbsolutePath();
System.out.println(absolutePath);
`
After executing below code i am getting the following path-
On 32-bit
C:\Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
On 64-bit
C:\Program Files (x86)\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf
I am not aware of your concern.
Just give a try to:
request.getServletContext().getRealPath("/")
It will give you the context path of your application Root folder regardless of underlying platform and you can add required folder or file's relative path (Relative path from application root folder ) with it to get absolute path.

file path Windows format to java format

I need to convert the file path in windows say C:\Documents and Settings\Manoj\Desktop for java as C:/Documents and Settings/Manoj/Desktop .
Is there any utility to convert like this.?
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
path = path.replace("\\", "/");
// or
path = path.replaceAll("\\\\", "/");
Find more details in the Docs
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
String javaPath = path.replace("\\", "/"); // Create a new variable
or
path = path.replace("\\", "/"); // Just use the existing variable
Strings are immutable. Once they are created, you can't change them. This means replace returns a new String where the target("\\") is replaced by the replacement("/"). Simply calling replace will not change path.
The difference between replaceAll and replace is that replaceAll will search for a regex, replace doesn't.
Java 7 and up supports the Path class (in java.nio package).
You can use this class to convert a string-path to one that works for your current OS.
Using:
Paths.get("\\folder\\subfolder").toString()
on a Unix machine, will give you /folder/subfolder. Also works the other way around.
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Just check
in MacOS
File directory = new File("/Users/sivo03/eclipse-workspace/For4DC/AutomationReportBackup/"+dir);
File directoryApache = new File("/Users/sivo03/Automation/apache-tomcat-9.0.22/webapps/AutomationReport/"+dir);
and same we use in windows
File directory = new File("C:\\Program Files (x86)\\Jenkins\\workspace\\BrokenLinkCheckerALL\\AutomationReportBackup\\"+dir);
File directoryApache = new File("C:\\Users\\Admin\\Downloads\\Automation\\apache-tomcat-9.0.26\\webapps\\AutomationReports\\"+dir);
use double backslash instead of single frontslash
so no need any converter tool just use find and replace
"C:\Documents and Settings\Manoj\Desktop"
to
"C:\\Documents and Settings\\Manoj\\Desktop"
String path = "C:\\Documents and Settings\\someDir";
path = path.replaceAll("\\\\", "/");
In Windows you should use four backslash but not two.

Getting the directory name in java

How do I get the directory name for a particular java.io.File on the drive in Java?
For example I have a file called test.java under a directory on my D drive.
I want to return the directory name for this file.
File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
Remember, java.io.File represents directories as well as files.
With Java 7 there is yet another way of doing this:
Path path = Paths.get("d:/test/test.java");
Path parent = path.getParent();
//getFileName() returns file name for
//files and dir name for directories
String parentDirName = path.getFileName().toString();
I (slightly) prefer this way, because one is manipulating path rather than files, which imho better shows the intentions. You can read about the differences between File and Path in the Legacy File I/O Code tutorial
Note also that if you create a file this way (supposing "d:/test/" is current working directory):
File file = new File("test.java");
You might be surprised, that both getParentFile() and getParent() return null. Use these to get parent directory no matter how the File was created:
File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();
Say that you have a file called test.java in C:\\myfolder directory. Using the below code, you can find the directory where that file sits.
String fileDirectory = new File("C:\\myfolder\\test.java").getAbsolutePath();
fileDirectory = fileDirectory.substring(0,fileDirectory.lastIndexOf("\\"));
This code will give the output as C:\\myfolder

Categories

Resources