How can I modify files at server by servlet? - java

I need to modify html file that is placed at server folder from my servlet.
No other way than read it by FileInputStream to byte[], convert to String[] splitting lines by "\n", change what I need and then rewrite it.
I don't see.

This is not possible by design. Your server might just have to serve a .WAR file. If the server is not configured to unzip it, your server will have to read all files directly from this archive. You can now guess that you cannot write at this location.
You would need to create some kind of working directory and also serve files from there, too. You can always use this directory as working directory:
File workingDir = (File)servletContext.getAttribute(ServletContext.TEMPDIR);

Related

Java FileNotFoundException when trying to read txt file from resources folder

I'm trying to read a text file located in src/main/resources/test/file.txt. I'm trying to get the path of the file using String path = getClass().getResource("/text/file.txt").getFile(); but when I try to read it I get a FileNotFoundException. I tried putting many different paths, all of which failed. How can I go about doing this?
The idea of putting something into the src/main/resources tree is that it will be copied into the JAR file that you build from your project. It will then be available to your application via the Class methods getResource(String) and getResourceAsStream(String) methods.
When you are running in your application in the development environment, it is certainly possible to use FileInputStream etcetera to access the resource. But this won't work in production. In production, the resources will then be inside your app's JAR file. FileInputStream cannot open a JAR file and its contents by name.
When you do this:
getClass().getResource("/text/file.txt");
you get a URL for the resource, which will look something like this:
jar:file:/path/to/your.jar!/text/file.txt"
It is not possible to turn that into a pathname the FileInputStream will understand. Whatever you try will give you a FileNotFoundException ... or something that is not the resource you want to read.
So what to do?
You have a few options, depending on your application's requirements.
You can use getResourceAsStream and use the resulting input stream directly.
You can copy the contents of getResourceAsStream to a temporary file, and then use the pathname of the temporary file.
You can create an application specific directory (e.g. in the user's home directory) and extract the file you need from the JAR into the directory. You might do this the first time the application runs.
You could open the JAR file as a JarFile and use that API to open an InputStream for the resource. But this assumes that that the resources are in a JAR ... and on some platforms (e.g. Windows) you may encounter problems with file locking. (And it would be a bad idea to attempt to update the resource in the JAR.)
Try giving complete path of the file from the disk.
C:\Users\MyUser\Desktop\file name with extension

Where does tomcat keep the files it is instructed to read?

I need some help here. It is redicolous, but my TomCat just does not take the file I want. I am trying to read some properties from a xml file. When I startup tomcat with the WAR file inside it makes a folder "MyApp".
My program points to MyApp\WebContent\myXmlFile.xml
It used to work fine, but i needed to edit the myXmlFile.xml so I did by adding two more properties, but it just doesnt read the new data. How is this even possible? I keep removing the "MyApp" folder from inside tomcat\webapps\ so it makes a new one, but it just keeps getting other data. My code is refreshed, but this file doesn't.
Some help would be appreciated a lot.
I am running Tomcat 7
More detail:
The myXmlFile.xml is inside the WAR file. I am not modifying it in runtime. It is suppose to be some sort of a configuration file. It reads the file once everytime there is a call done to this function. It just reads the xml files and puts properties inside a string.
When i upload the WAR file. I will first use shutdown.bat, than I will use startup.bat when the WAR file is in webapps.
Try restarting Tomcat. In Linux, type
/etc/init.d/tomcat8 restart
Ensure you don't have any other copy of this file with the old values in another folder. I would try to delete (or rename) myXmlFile.xml from the WAR and see what is generated in the Tomcat deploy folder.

why doesn't my jspSmartUpload code work?

I want to implement an upload component in my servlet file,but it doesn't work.
The code episode seems like follows:
SmartUpload smartUpload=new SmartUpload();
StringBuffer stringBuffer=new StringBuffer();
smartUpload.initialize(config,request, response);
try {
smartUpload.upload();
File file=smartUpload.getFiles().getFile(0);
stringBuffer.append(file.getFileName());
file.saveAs("/upload_resources/"+stringBuffer);
} catch (SmartUploadException e) {
e.printStackTrace();
}
The upload_resource directory is just under the WebRoot directory,the code runs without any errors ,but the file is just not uploaded. By the way , even I changed the line
file.saveAs("/upload_resources/"+stringBuffer);
to
file.saveAs(request.getRealPath("/upload_resources/")+"/"+stringBuffer);
that is to use an absolute path, the file is not uploaded.
Any help will be appreciate. Thanks.
I've never really worked with SmartUpload, but I can tell that you shouldn't be saving uploaded files in the webapp's deploy folder. They may all get lost whenever the webapp get redeployed with the simple reason that the uploaded files are not contained in the original WAR file. So you should not prepare the upload folder in the webapp's deploy folder, but on a fixed path outside the deploy folder.
If SmartUpload is well designed, I'd expect that
file.saveAs("/upload_resources/"+stringBuffer);
will save it to the /uploaded_resources folder on the root of the same disk as where the webserver is started from. So in for example Windows that would be C:\uploaded_resources. Prepare and use that folder instead.
Further there's another potential problem when you're using the MSIE browser. This browser namely incorrectly includes the full client side path in the filename. I'm not sure if SmartUpload handles this properly, but you might want to debug the actual value of file.getFileName() and make sure that it's really only the filename in the form of filename.ext. Otherwise, you'd need to use String#substring() to substring the part after the last / and \.

Best Location for Uploading file [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 7 years ago.
Working on some import process where i need to first upload the file at some location on server and than later on i need to pick the file from this location to import it in to the system.
i am just wondering what might be the best place to store the uploaded file. i have few option
1) Can create a folder in the root of tomcat and than can place the upload files there and later on can pick the file for the import process.
File dir = new File(System.getProperty("catalina.base"), "uploads");
is this a good option and weather the above code will work equally in all enviornment
2) i can create an uploads folder undermy application and can access it for file upload and later on for import by using the following code
ServletActionContext.getServletContext().getRealPath("uploads");
your valuable suggestions are needed the only work i need to do is to upload the file and den run the import process for the uploaded files(s) and once import is successfull remove files from this folder to other like processed etc.
File dir = new File(System.getProperty("catalina.base"), "uploads");
It won't work on environments where catalina.base property is absent. So you need to either document it properly in the installation manual of the webapp to ensure that this property is been set on the server machine in question, or to look for an alternative approach.
ServletActionContext.getServletContext().getRealPath("uploads");
This is not a good choice as permanent storage. Everything will get lost whenever you redeploy the WAR.
Rather store it in a known and fixed path outside your webapp and add its path as <Context> in Tomcat's /conf/server.xml so that it's available online as well.
If you don't want to alter the Tomcat's /conf/server.xml for some reason, then you need to create a servlet which reads the file from disk using FileInputStream and writes it to the OutputStream of the response. You can find here a basic example.
Related questions:
Simplest way to serve static files from outside application server

write log files in my webapps/application directory on tomcat

I write a flex + java application using the blazeds framework.
when i write log files in my java classes the default path is the java path on the server.
I want it to be my application at the tomcat/webapps/application directory
when i write it hard-coded it failed (maybe bacause of permissions)
but, i want it to be general (not hard-coded)
so, what do i need to change in my java code in order to write files in my webapps directory?
maybe it just an xml configuration?
what do i need to do?
thank you!
Ok. I need to use this method: System.getProperty("catalina.base")
OK, so you've figured out how to do it.
But I'd like to suggest to you that it is a better idea to put log files in $CATALINA_HOME/logs. The problem with putting log files in $CATALINA_HOME/webapps/yourApp is that they are liable to be clobbered if you redeploy your WAR file.
also easy cheezy on unix is to put a symlink in your webapps/application directory to the log directory and add log to the url.

Categories