2011-03-16 64 views
2

我有一個使用數據文件的servlet。該文件的相對路徑包含在web.xml中。 我有以下的代碼部分,它從文件讀取數據:Java Servlet - 將數據寫入文件

public class LoginServlet extends HttpServlet { 
private Map<String, UserData> users; 
public void init() throws ServletException { 
    super.init(); 
    String userFilePath = getServletContext().getInitParameter("user.access.file"); 
    InputStream userFile = this.getClass().getResourceAsStream(userFilePath); 
    try { 
     users = readUsersFile(userFile); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     throw new ServletException(e); 
    } 
      .... 
      .... 
    } 

private Map<String, UserData> readUsersFile(InputStream is) throws IOException{ 
    BufferedReader fileReader = new BufferedReader(new InputStreamReader(is)); 
    Map<String, UserData> result = new HashMap<String, UserData>(); 
      .... 
      .... 
      .... 
      return result; 
    } 
} 

因爲這是一個servlet,它不僅會在我的電腦上工作,我不能使用絕對路徑。 有誰知道我可以如何使用類似的方式將數據寫入文件?

+0

究竟是什麼問題?你不能在你的web.xml中使用絕對路徑,因爲你想讓它可配置?或者你是否得到某種你不明白的異常?您可以將數據寫入文件,請記住,servlet運行在需要操作系統文件寫入權限才能寫入目錄的servlet容器進程中。 – ivy

+0

請說明是否要將文件寫入服務器或客戶端主機? – anubhava

回答

0

如果資源URL是resolveable爲絕對本地磁盤文件系統路徑,它是可寫的,那麼你可以使用

URL url = this.getClass().getResource(userFilePath); 
File file = new File(url.toURI().getPath()); 
OutputStream output = new FileOutputStream(file); 
// ... 

然而,這又不能保證在所有環境下工作。

最好的辦法是有一個固定的和絕對的本地磁盤文件系統路徑。然而,通常的做法是將結構化數據(用戶名/密碼)存儲在數據庫中而不是文件中。