Save file with relative path from javabean or servlet - java

I need to save file from javabean or servlet, and I'm having trouble finding relative path, I tried:
(from servlet)
ServletContext servCont = this.getServletContext();
String contextPath = servCont.getRealPath(File.separator);
System.out.println("REAL PATH: "+ contextPath);
this gives me:
REAL PATH: E:\Web\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Saloni\
and project folder is:
E:\Web\Saloni
and from bean (bean is called Salon)
String path = Salon.class.getResource("Salon.class").getPath();
and got basically the same thing
/E:/Web/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Saloni/WEB-INF/classes/beans/Salon.class
If I just put file name into FileOutputStream file gets saved in eclipse workspace.
I read somewhere that I'm supposed to get to WEB-INF somehow but can't do that ..

Related

Get file name (with path) from resources

I'm using camel to create some routes.
I have a file in the resources folder and I only want the file path + name. Not the content.
When I use:
from(URI)
.log("resource:classpath:llave.txt")
I got the content of llave.txt but I need something like
C:\something\llave.txt
Thanks!!
Edit for clarity: I do not need the file information from a File endpoint (also, is easy get that info using file language or the exchange's header).
I need the info of a file located in the resource folder in the project.
Get the file:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("llave.txt").getFile());
Get the path:
//full path ( including the file )
String absolutePath = file.getAbsolutePath();
// path only
String filePath = absolutePath.
substring(0, absolutePath.lastIndexOf(File.separator));
You can access the path using the headers that Camel sets after calling the File component:
from(URI)
.log("$simple{headers.CamelFileAbsolutePath}")
You can read more about the File component here:
http://camel.apache.org/file2.html
With java.nio you can get the full path:
String fullPath = Paths.get(getClass().getResource("llave.txt").toURI()).toString();
And the file name:
String fileName = Paths.get(getClass().getResource("llave.txt").toURI()).getFileName();

Unable to check if file exists or not in web project

I have a pdf file in my web project at the below location :
"static/Downloadables/20/Home_insurance_booklet.pdf "
"static" is present in the WebContent. The context root of the project is "pas".
In one of the jsp, I need to check if the file Home_insurance_booklet.pdf exists or not. I tried in many ways but unable to succeed. Below is the code I have used.
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
Through the file exists, the condition is returning false. How to check if the file exists or not w.r.t to certain location in the root of the web project ?
Edit:
File path displayed is
/pas/static/Downloadables/20/Home_insurance_booklet.pdf
Try the following:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
And here is the API-Doc of getRealPath():
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Use
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
The ServletContext#getRealPath() converts a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root.
After that append in this way :
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
Then use
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
check whether file is loaded in the project or not. and then try for absolute path first of the file in your code then try for relative path.
You have to use a file system based URL instead of relative web based URL.

path till WEB-INF inside web application

I am parsing the HttpRequest inside a web application. My servlet extends HttpServlet
I need to find the path till WEB-INF inside a WAR file so that file present inside WEB-INF can be accessed.
I cannot use Realpath so there has to be some alternative.
tried using
ServletContext servletContext = getServletContext();
InputStream input = servletContext.getResourceAsStream("/WEB-INF");
but everytime
Sysem.out.println(input) returns null
Please suggest.
You can get the root web directory of your application like this:
servletContext.getRealPath(File.separator));
So assuming your WEB-INF is in there, you could do this:
servletContext.getRealPath(File.separator + "/WEB-INF/whatever.file"));
It returns a String path, so to actually get the file:
new File(servletContext.getRealPath(File.separator + "/WEB-INF/whatever.file")));

Use Relative path in place of absolute path

First of all i request people do not consider it as a duplicate question, please look into query.
I am copying the xml files from one folder to other folder, in the source folder, i have some files which have some content like "backingFile="$IDP_ROOT/metadata/iPAU-SP-metadata.xml" but while writing to the destination folder.
i am replacing the "$IDP_ROOT" with my current working directory. The entire copying of files is for deploying into tomcat
server. The copying is done only when server starts for the first time.
Problem: If i change the folder name from my root path in my machine after i run the server,
the entire process will be stopped because the destination folder files already contains the content which is with
existed files names or folder names.
So i want to change it to relative path instead absolute path. What is the best way to do it?
Please look at code below:
// Getting the current working directory
String currentdir = new File(".").getAbsoluteFile().getParent() + File.separator;
if(currentdir.indexOf("ControlPanel")!=-1){
rootPath=currentdir.substring(0, currentdir.indexOf("ControlPanel"));
}else{
rootPath=currentdir;
}
rootPath = rootPath.replace("\\", "/");
// target file in source folder is having "backingFile="$IDP_ROOT/metadata/iPAU-SP-metadata.xml"
String content = FileReaderUtil.readFile(targetFile,
rootPath + "Idp/conf");
content = updatePath(content, Install.rootPath
+ "IdP/IdPserver/metadata","$IDP_ROOT");
FileWriterUtil.writeToFile(Install.rootPath
+ "IdP/IdPserver/idp/conf", content,
targetFile);
// update method
public String updatePath(String content, String replaceString,String replaceKey) {
replaceKey = replaceKey!=null ? replaceKey : "$IDP_SERVER_ROOT";
replaceString= replaceString.replace("\\","/");
String updateContent = content.replace(replaceKey,
replaceString);
return updateContent;
}

dynamic path in java application

I want to specify the path dynamically. myapp/CopyFolder and myapp/RunFolder's are inside application like myapp/WEB-INF. The code I have given below is in .java file(in eclipse) and in .class file(in tomcat inside myapp/WEB-INF/classname/packagename/). My deployment is in tomcat.
try {
functionNamesObject.Integration(
".txt",
path+"\\CopyFolder",
path+"\\RunFolder",
"app.exe",
"Input.txt"
);
I want path to be dynamic when I call above function. I tried with getResource("MyClass.class") ,new File("").getAbsolutePath(); and System.getProperty("user.dir") but no use. Is there any other way?
You can get the path value as below:
URL resource = getClass().getResource("/");
String path = resource.getPath();
This will return the absolute path to to your myApp/WEB-INF/classes directory.

Categories