【问题标题】:Java Writing to Properties File Not WorkingJava 写入属性文件不起作用
【发布时间】:2017-08-28 23:53:14
【问题描述】:

由于某种原因,以下代码(在我的程序中被 try-catch 语句包围)无法正常工作,因为它继续抛出 NumberFormatException, 并且还会擦除属性文件中的信息。感谢您的帮助。

        File propFile = new File("path\to\file\properties.properties");
        FileOutputStream outStream  = new FileOutputStream(propFile);
        FileInputStream inStream = new FileInputStream(propFile);

        Properties prop = new Properties();
        prop.load(inStream);

        out.println(prop.getProperty("entryID"));

        prop.setProperty("entryID", Integer.toString(Integer.parseInt(prop.getProperty("entryID"))+1));

        prop.store(outStream, "");

【问题讨论】:

  • out 是一个 PrintWriter 对象,顺便传递给包含上述代码的函数。
  • 打印结果如何?
  • 属性文件的内容很可能会显示问题所在。我的猜测是属性文件格式错误。输出将被FileOutputStream 清除。
  • 第一次执行代码应该是0,然后每次执行加一
  • FileOutputStream outStream = new FileOutputStream(propFile); 清除 propFile,因为该构造函数截断

标签: java properties-file


【解决方案1】:

只需更改顺序,您在阅读内容之前创建 FileOutStream 对象

请找到附加的工作sn-p

文件 propFile = new File("path\to\file\properties.properties");

    FileInputStream inStream = new FileInputStream(propFile);

    Properties prop = new Properties();
    prop.load(inStream);

    System.out.println(prop.getProperty("entryID"));

    prop.setProperty("entryID", Integer.toString(Integer.parseInt(prop.getProperty("entryID"))+1));
    FileOutputStream outStream  = new FileOutputStream(propFile);
    prop.store(outStream, "");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2018-01-11
    • 2017-03-30
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多