我尝试更新.properties文件时出现异常

时间:2015-03-03 05:35:05

标签: java

在servlet中,我从表单获取值并尝试使用表单值更新属性文件值。但是我得到了java.io.IOException。请告诉我如何克服此问题并更新我的属性文件。如果我更新属性文件,我将能够看到.properties文件中的更改。 的Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String name=request.getParameter("appName");
    String link=request.getParameter("appLink");
    String database=request.getParameter("appDB");
    String webServices=request.getParameter("appWebService");
    FileInputStream in = new FileInputStream("server_url.properties");
    in.close();
    Properties props = new Properties();
    props.load(in);
    FileOutputStream outputStream = new FileOutputStream("server_url.properties");
    props.setProperty("DemoApps_Links", link);
    props.setProperty("DemoApps_DataBase", database);
    props.store(outputStream , null);
    outputStream.flush();
    outputStream.close();
System.out.println(link);
System.out.println(database);
}

堆栈跟踪

java.io.IOException: Stream Closed
java.io.FileInputStream.readBytes(Native Method)
java.io.FileInputStream.read(FileInputStream.java:243)
java.util.Properties$LineReader.readLine(Properties.java:434)
java.util.Properties.load0(Properties.java:353)
java.util.Properties.load(Properties.java:341)
com.monitoring.servlets.updateDetails.doPost(updateDetails.java:38)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

2 个答案:

答案 0 :(得分:1)

查看堆栈跟踪java.io.IOException: Stream Closed,似乎问题是您的FileInputStream关闭语句位置错误。 您先关闭它in.close(),然后在下一个语句props.load(in)中阅读它。

最后尝试编写in.close()语句。

答案 1 :(得分:0)

问题是你正在关闭流(in.close();),之后你正在加载它(props.load(in);

最佳做法是在结束时关闭

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String name=request.getParameter("appName");
    String link=request.getParameter("appLink");
    String database=request.getParameter("appDB");
    String webServices=request.getParameter("appWebService");
    FileInputStream in = new FileInputStream("server_url.properties");

    Properties props = new Properties();
    props.load(in);
    FileOutputStream outputStream = new FileOutputStream("server_url.properties");
    props.setProperty("DemoApps_Links", link);
    props.setProperty("DemoApps_DataBase", database);
    props.store(outputStream , null);
    outputStream.flush();
    outputStream.close();
System.out.println(link);
System.out.println(database);
in.close();
}