如何在 TXT 中存储数据(使用 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 中编写文件?

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

<%
FileWriter writer = null;
String text = request.getParameter("texto");
try{
    String path = application.getRealPath("/") + "prueba.txt";
    writer = new FileWriter(path);
    writer.write(text);
    writer.flush();
}catch(Exception e){
    e.printStackTrace();
}
%>

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

您也可以尝试调用 FileWriter 的 flush 方法(但如果调用关闭,则不需要这样做(。这是因为FileWriter的默认字符大小为1024个字符(检查java.io.Writer(。当您将内容写入固件时,它首先将内容移动到缓冲区,每当它超过 1024 限制或关闭固件时,它会将 bufer 内容保存到磁盘。因此,通过手动调用 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();
        }
    }

最新更新