Create file in jsp server

When I create a file in java servlet

, I cannot find this file to open. This is my code in servlet

:

FileOutputStream fout;
    try {
        fout = new FileOutputStream("title.txt");
        new PrintStream(fout).println(request.getParameter("txttitle"));
        fout.close();
        System.out.println(request.getParameter("txttitle"));
    } catch (Exception e) {
        System.out.println("I can't create file!");
    }

      

Where can I find this file?

+3


source to share


4 answers


if you first create the file like in

File f = new File("title.txt");
fout = new FileOutputStream(f);

      



then you use getAbsolutePath

to return the location where it was created.

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

      

+2


source


Since you did not specify any directory for the file, it will be placed in the default directory of the process that starts your servlet container.

I would recommend that you always give the full path to your file when doing this kind of action.



If you are using tomcat, you can use System.getProperty ("catalina.base") to get the path to the tomcat base directory. This can sometimes help.

+1


source


Create a file file and make sure the file exists: -

File f = new File("title.txt");
if(f.exists() && !f.isDirectory()) { 
fout = new FileOutputStream(f);
new PrintStream(fout).println(request.getParameter("txttitle"));
fout.close();
System.out.println(request.getParameter("txttitle"));
}

      

If the servlet cannot find the file, provide the full path to the specified file, for example new File("D:\\Newfolder\\title.txt");

0


source


you must first check if the file doesn't exist, create it

if(!new File("title.txt").exists())
{
   File myfile = new File("title.txt");
    myfile.createNewFile();
}

      

then you can use FileWriter or FileOutputStream to write to file which I prefer FileWriter

FileWriter writer = new FileWriter("title.txt");
writer.write("No God But Allah");
writer.close();

      

just simple

0


source







All Articles