简体   繁体   English

在jsp servlet中创建文件

[英]Create file in jsp servlet

When I create a file in java servlet , I can't find that file for opening. 当我在java servlet创建一个文件时,我无法找到该文件进行打开。 This is my code in servlet : 这是我在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? 我在哪里可以找到该文件?

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 然后使用getAbsolutePath返回创建它的位置

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

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. 由于您没有为文件指定任何目录,因此它将被放置在运行servlet容器的进程的缺省目录中。

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. 如果您正在运行tomcat,则可以使用System.getProperty(“catalina.base”)来获取tomcat基目录的路径。 This can sometimes help. 这有时会有所帮助。

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"); 如果servlet找不到文件,则给出指定文件的完整路径,如new File("D:\\\\Newfolder\\\\title.txt");

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或FileOutputStream写入我更喜欢FileWriter的文件

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

simply simple 简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM