简体   繁体   English

Java Servlet-将数据写入文件

[英]Java Servlet - write data to file

I have a servlet which uses file with data. 我有一个使用数据文件的servlet。 The relative path to this file is contained in web.xml. 该文件的相对路径包含在web.xml中。 I have following part of code, which reads data from file: 我有以下代码部分,它从文件读取数据:

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;
     }
}

Because this is a servlet and it will not work only on my PC, I can't use absolute path. 因为这是一个servlet,并且它仅在我的PC上不起作用,所以我不能使用绝对路径。 Does anyone know how I can write data to the file, using a similar way? 有谁知道我可以使用类似的方式将数据写入文件吗?

If the resource URL is resolveable to an absolute local disk file system path and it is writable, then you can use 如果资源URL可解析为绝对本地磁盘文件系统路径并且可写,则可以使用

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

This is however in turn not guaranteed to work on all environments. 但是,这又不能保证在所有环境下都能正常工作。

Your best bet is really to have a fixed and absolute local disk file system path. 最好的选择是拥有固定且绝对的本地磁盘文件系统路径。 The normal practice is however to store structured data (usernames/password) in a database and not a file. 但是,通常的做法是将结构化数据(用户名/密码)存储在数据库中而不是文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM