如何在txt中存储数据(使用jsp)

时间:2017-05-20 11:29:24

标签: java eclipse file jsp

我一直在尝试使用下面的代码将一些数据存储在txt文件中

<%
FileWriter file = null;
String text = request.getParameter("texto");
try{
    String path = application.getRealPath("/") + "prueba.txt";
    file = new FileWriter(path);
    file.write(text);

}catch(Exception e){
    e.printStackTrace();
}
%>

但是当我尝试打开此文件时,该文件为空,我该如何解决?还有另一种在jsp中编写文件的更好方法吗?

2 个答案:

答案 0 :(得分:0)

您还应该调用FileWriter类的flush方法(如果不再写,则关闭方法)。例如:

ORG 0h

MOV dptr, #40h

loop:   
    MOV A, #0
    MOVC A, @A+DPTR
    INC DPTR
    INC R0
    MOV R1, #table_end - table_start
    CJNE R0, #table_end - table_start, loop

ORG 40h
table_start:        DB 1,2,4
table_end:

END

答案 1 :(得分:0)

处理这种情况的正确方法是通过调用close()方法手动关闭FW。这会将缓冲的内容保存到磁盘。

此外,您可以尝试调用FileWriter的flush方法(但如果您的调用关闭,则不需要这样做)。这是因为FileWriter的默认缓冲区大小为1024个字符(请检查java.io.Writer)。当您将内容写入FW时,首先将内容移动到缓冲区,每当超过1024限制或关闭FW时,它会将缓冲内容保存到磁盘。因此,通过手动调用flush()方法,您可以将缓冲的内容保存到磁盘,而无需等待close()或超过1024限制。

    FileWriter file = null;
    String text = request.getParameter("texto");
    try{
        String path = application.getRealPath("/") + "prueba.txt";
        file = new FileWriter(path);
        file.write(text);

        //This is not necessary if you closing the FW
        file.flush(); 

    }catch(Exception e){
        e.printStackTrace();    

    }finally {

        try {

            if (file != null)
                file.close();
        } catch (IOException ex) {

            ex.printStackTrace();

        }

    }