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?
source to share
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.
source to share
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");
source to share
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
source to share