Farshid Shekari
Farshid Shekari

Reputation: 2449

Create file in jsp servlet

When I create a file in java servlet, I can't find that file for opening. 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 I can find that file?

Upvotes: 3

Views: 3855

Answers (4)

Mawardy
Mawardy

Reputation: 3838

you should check first 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 the file i prefer FileWriter

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

simply simple

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44854

if you create file first as in

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

then you use getAbsolutePath to return the location of where it has been created

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

Upvotes: 3

Maurice Perry
Maurice Perry

Reputation: 32831

Since you have'nt specified any directory for the file, it will be placed in the default directory of the process that runs your servlet container.

I would recommand you to always specify the full path of your your file when doing this kind of things.

If you're running tomcat, you can use System.getProperty("catalina.base") to get the path of the tomcat base directory. This can sometimes help.

Upvotes: 1

Mustafa sabir
Mustafa sabir

Reputation: 4360

Create a file object 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 give the full path to the file specified, like new File("D:\\Newfolder\\title.txt");

Upvotes: 0

Related Questions