2012-06-30 110 views
1

我使用提交按鈕創建HTML輸入表單。表單動作將我們帶到一個jsp頁面。 我寫這個我JSP頁面上JSP寫入文本文件

 ServletContext context = this.getServletContext(); 

     String path = context.getRealPath("WEB-INF/list.txt"); 


     User user = new User(fName, lName, eAddress, phone, company, webinar,dateObj); 
     UserIO.add(user, path); 

然後,我創建了一個名爲UserIO

public class UserIO { 

    public static void add(User user, String path) throws IOException 
    { 
     FileOutputStream fos= new FileOutputStream(path, true); 

     PrintWriter out = new PrintWriter(fos);//, true)); 

     out.println(user.getFname() + "|" + user.getLname() + "|" + user.getEmail() + "|" ); 
     out.println(user.getPhone() + "|" + user.getCompany() + "|" + user.getWebinar() + "|" + user.getDate()); 

     out.close(); 
    } 

} 

現在我的問題是,輸出顯示在JSP頁面中,但不保存到文本文件中的Java類。

我已經在Netbeans中完成了這個程序並保存了<projectname>/web/WEB-INF下的文件。

我試圖將路徑更改爲<projectname>/web/WEB-INF/list.txt,但放棄了錯誤信息。所以堅持像上面那樣改變它。

告訴我你的專家opion如何解決這個問題?

回答

0

您必須提供FileOutputStream正確的路徑!
是否有任何文件夾,您的eclipse目錄中名爲WEB-INF。我想不是!
嘗試使用這些線路來了解正在創建的文件,其中:

File file = new File("list.txt"); 
System.out.println(file.getCanonicalFile()); 


+0

我在netbeans中這樣做。當我創建Java Web應用程序時 - 創建WEB-INF文件夾。 –

+0

但我不認爲它在NetBeans(應用程序)文件夾中。我相信WEB-INF是在你的工作空間的某個地方創建的,完全不同。照我說的去做,你會看到創建文件的位置。 –

0

我想,我找到你的答案:
嘗試使用這樣的:

(我假設該文件被找到)
要寫在你的文件,你應該用這些代碼替換你的代碼:

FileOutputStream fos= new FileOutputStream(path, true); 
fos.write((user.getFname() + "|" + user.getLname() + "|" + user.getEmail() + "|").getBytes()); 
fors.write((user.getPhone() + "|" + user.getCompany() + "|" + user.getWebinar() + "|" + user.getDate()).getBytes()); 


完成!

1

查找項目build \ web \ WEB-INF \'目錄()中的txt文件。 我面臨同樣的問題,然後我在給定的目錄中找到了文本文件。 :-)順便說一句,我說的是,如果你使用Netbeans IDE ..