File upload to the server directory - java

I am uploading an excel file to the tomcat server. Which is saving inside my eclipse directory D:\workspace_Eclipse\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\StatusPortal\Job_doc\abc.xls
When ever i am accessing this file its giving me file not found Exception \Job_doc\abc.xls.
Its could not able to find the path which is i am giving while accessing the file like
\Job_doc\abc.xls
I am giving the path \Job_doc\abc.xls while accessing.

This is because you are using a relative path. Eclipse will use the current working directory to be a temp location for deploying the webapp. So the file is uploaded to the folder relative to this path (This happens when you start the app from eclipse Run On Server. Define your paths as static constants(May be you can use absolute paths for testing). After testing you can use the relative paths on production deployment.
Still, you can do alternate way. Dont use the integrated tomcat server of Eclipse. Use a standalone server, use the descriptor file to link the webapp in workspace to tomcat. After the save, just reload the app in tomcat manager and try.

Try reading your file using ClassLoader as below:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("/Job_doc/abc.xls");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream ));
If you want to get the File object, then try as below:
URI uri = getClass().getClassLoader().getResource("/Job_doc/abc.xls").toURI();
File file = new File(uri);

Related

How to upload an image to web resource folder in tomcat or glassfish

I tried to upload an image to tomcat and glassfish servers, Path I tried to set is as bellow System.getProperty("user.dir")+ File.separator+"images"+File.separator;
It takes System.getProperty("user.dir") as tomcat C:\Apache\Tomcat\bin and glassfish 'C:\Apache\glassfish4\glassfish\domains\domain1\config` directory. I am using Intellij to develop the system.
I want to upload an image to out/artifacts/CopywriteProtector_war)exploded/Resources/images folder so that I can access the images using http://localhost/Resources/images/msg.jpg, how to do this? I have spent days of time googling but couldn't able to find useful thing
You can get the root of your deployed application with
String root = getServletContext().getRealPath("/");
This will be the equivalent of the resources directory of your source code.
Add the filepath of where you want your image to be. i.e.
String filePath = root + "images/msg.jpg";
Then you can created your writer from that path
BufferedWriter writer = new BufferedWriter(new FileWriter(filepath);
writer.write(objectToWrite);//or similar
You can then access the resulting file with
getServletContext().getResource(filePath); // as URL or
getServletContext().getResourceAsStream(filePath); // as InputStream
-- Tested and worked on Payara (an application server derived from Glassfish)

unable to get file using classLoader.getResource(fileName).getFile()

I made a maven web-app project in eclipse it was working fine on the machine on which I made this. but when importing this project to other machine in eclipse it gives me this exception while getting the file:
exception:D:\Eclipse%20Workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\example\WEB-INF\classes\file.txt
(The system cannot find the path specified)
I am using this code to get a file:
public File getFile (String fileName) {
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
return file;
}
the file is in the resources folder of the project:
D:\Eclipse Workspace\Sentiment Analysis\example\src\main\resources
I go the path the exception message showing and found that the file is already been there.
The getFile method of URL does not convert a URL to a file. It just returns the portion of the URL after the host and port. URLs need to percent-escape a lot of characters, including spaces, so you cannot reliably use the URL's path portion as a file name. In fact, the exception is telling you exactly that: There is no directory named D:\Eclipse%20Workspace.metadata.plugins on your computer. (Go ahead and check.)
When you have a URL, you should not be trying to convert it to a File at all. You don't need to. You can read from a URL just as easily as from a file using the openStream method of URL.
But even that is not necessary, because you can also use the getResourceAsStream method to skip the URL entirely and get a readable InputStream:
InputStream stream = getClass().getResourceAsStream("/file.txt");
The code is looking for the file in the same directory as this code class resident. What is the package structure of this code?
Also, only Maven copy the resources into the class path. So if you compile and run using Eclipse then the resources folder won't be copied automatically.

retrieve value from servlet and store in xml file [duplicate]

I am trying to generate a XML file and save it in /WEB-INF/pages/.
Below is my code which uses a relative path:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).
But when deploying and running on server machine, it throws the below exception:
javax.xml.transform.TransformerException:
java.io.FileNotFoundException
C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?
Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.
Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.
Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.
Always write them to an external folder on a predefined absolute path.
Either hardcoded:
File folder = new File("/absolute/path/to/web/files");
File result = new File(folder, "filename.xml");
// ...
Or configured in one of many ways:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
Or making use of container-managed temp folder:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
Or making use of OS-managed temp folder:
File result = File.createTempFile("filename-", ".xml");
// ...
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
See also:
Recommended way to save uploaded files in a servlet application
Where to place and how to read configuration resource files in servlet based application?
Simple ways to keep data on redeployment of Java EE 7 web application
Store PDF for a limited time on app server and make it available for download
What does servletcontext.getRealPath("/") mean and when should I use it
getResourceAsStream() vs FileInputStream
just use
File relpath = new File(".\pages\");
as application cursor in default stay into web-inf folder.

Where should I place external xslt file in java web app?

I have an external XSLT file that I'm placing in the /WEB-INF/classes/ folder. How should I use relative path to access the file?
File xsltfile = new File("xhtml2fo.xsl");
gives a FileNotFoundException at D:\Softwares\eclipse\xhtml2fo.xsl.
I'm runnning the webapp on a tomcat server.
You can use ServletContext#getRealPath("/") to get the path to the WebContent root
Then Simply use this
String pathToFile = servletContext.getRealPath("/") + "/WEB-INF/classes/ folder/html2fo.xsl";
File file=new File(pathToFile);
The working directory in my tomcat launch configuration was D:/Softwares/eclipse and hence the relative path was being picked up from the same. It worked after I changed the working directory to ${workspace_loc:mywebapp/WebContent/WEB-INF} and file location as "classes/xhtml2fo.xsl"

How to create a file in src/main/resources

If I do this
fis = new FileInputStream(new File(".").getAbsolutePath() + "/sudoinput.txt");
Its trying to write to this location on the server. I am not sure if this is a writable
place.
FILE NAME (fos)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
FILE NAME (fis)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
I wanted to write to
webapps/sudoku/WEB-INF/classes
which is basically
C:\Users...\git\sudo-project\sudo\src\main\resources
On Eclipse Windows 7 I get this
error
src\main\resources\sudoinput.txt (The system cannot find the path specified)
if I give
fis = new FileInputStream("src/main/resources/sudoinput.txt");
I have tried this too:
fis = new FileInputStream("src\\main\\resources\\sudoinput.txt");
but doesn't work.
how should I create a fileinputstream to be able to write to src/main/resources ?
please note that I am using eclipse windows to do dev and will be uploading the .war file on to a unix server if this changes the way in which the paths need to be specified.
The src/main/resources folder is a folder that is supposed to contain resources for your application. As you noted, maven packages these files to the root of your file so that you can access them in your library.
Have a look at the Maven documentation about the standard directory layout.
In certain cases, it is possible to write to the context but it is not a good idea to try it. Depending on how your webapp is deployed, you might not be able to write into the directory. Consider the case when you deploy a .war archive. This would mean that you try to write into the war archive and this won't be possible.
A better idea would be to use a temporary file. In that way you can be sure this will work, regardless of the way your web application is deployed.
Agree with Sandiip Patil. If you didn't have folder inside your resources then path will be /sudoinput.txt or in folder /folder_name/sudoinput.txt. For getting file from resources you should use YourClass.class.getResource("/filename.txt");
For example
Scanner scanner = new Scanner(TestStats.class.getResourceAsStream("/123.txt"));
or
Scanner scanner = new Scanner(new `FileInputStream(TestStats.class.getResource("/123.txt").getPath()));`
Also look at: this
You can keep the file created under resources and call .class.getresource(your_file_name_or_path_separated_with_forward_slash);
See if it works for you.
If you like to create files in webapps/sudoku/WEB-INF/classes which is in the end within the created WAR file which can be achieved by putting the files you want into src/main/resources/
This means in other words you need to create the folder src/main/resources and put the files you like into this directory.

Categories

Resources