簡體   English   中英

如何將數據存儲在txt中(使用jsp)

[英]how to store data in a txt (using 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()方法來手動關閉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();

        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM