Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Servlets - Writing to file

I'm using the Netbeans IDE, and I'm currently using a GlassFish server. What I want to do is write to a file.

I looked at some pages, and the code I have now (that is not working as far as I know) looks like:

 File outputFile = new File(getServletContext().getRealPath("/")
            + "TheFile.txt");
    FileWriter fout = new FileWriter(outputFile);
    fout.write("The Content");
    fout.close();

This is my project's structure:

alt text

Also where will the file get placed?


Edit: I forgot to mention there are some other folders below the ones in the picture: Test Packages, Libraries, Test Libraries and Configuration Files. However I don't think the file would get placed there.

Edit (newest): I found out the file is stored in the /build/web folder, but this is not appearing in Netbeans. Even after I restarted it.

like image 726
whirlwin Avatar asked Dec 29 '22 04:12

whirlwin


2 Answers

As you've coded, the file will be placed in public web root. That's where getRealPath("/") will point to. To be precise, it's the folder named Web Pages as in your screenshot. As an exercise, do the following to figure the absolute path, so that you can find it by OS disk explorer.

System.out.println(file.getAbsolutePath());

I don't do Netbeans, but likely you need to refresh the folder in your IDE after the write of the file so that it appears in the listing in the IDE. Click the folder and press F5. This is at least true for Eclipse.

That said, this approach is not recommended. This won't work when the servletcontainer isn't configured to expand the WAR on disk. Even when it did, you will lose all new files and changes in existing files when the WAR is been redeployed. It should not be used as a permanent storage. Rather store it on a fixed path outside the webapp or in a database (which is preferred since you seem want to reinvent a CMS).

like image 106
BalusC Avatar answered Jan 09 '23 05:01

BalusC


Note that this is in no way guaranteed to work in all web containers or through restarts and will most likely be overwritten by a redeployment.

If you want to be able to allow your user to update content, you need to store the new content somewhere and have a servlet or a JSP-page or a facelet retrieve the new content from the backing storage and send it to the browser.

like image 20
Thorbjørn Ravn Andersen Avatar answered Jan 09 '23 06:01

Thorbjørn Ravn Andersen