public class Test {
public static void main(String[] args) {
Properties properties = new Properties();
String path = "data.properties";
File file = new File(path);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
} catch (IOException e) {
e.printStackTrace();
}
properties.setProperty("wmm", "123");
try {
properties.store(fileWriter,"first");
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请问一下 大家 那个环节出了问题。
解答如下,有帮助的话采纳一下哦!
先打印项目相对路径的根目录看看,然后看文件位置添加
System.out.println(System.getProperty(“user.dir”));
参考GPT的内容和自己的思路:
在该代码中,您已经成功地将属性写入了Properties对象,并将其存储到文件中。但是,在此之后,您需要关闭该文件以保存数据,并且您没有检查这是否成功。建议在关闭文件之前添加一些代码来检查是否已将数据成功写入文件,例如,可以添加以下代码:
properties.store(fileWriter,"first");
fileWriter.flush();
fileWriter.close();
// 重新加载文件并检查属性是否存在
Properties loadedProperties = new Properties();
FileInputStream in = new FileInputStream(file);
loadedProperties.load(in);
in.close();
System.out.println(loadedProperties.getProperty("wmm"));
这样,您可以在代码中检查属性是否已成功写入并存储到文件中。
有可能是路径问题,可以尝试指定一个绝对路径,例如 "C:/data.properties",以确保文件路径正确。如果文件路径正确,但文件仍然为空,则可能是你的代码没有写入数据成功。可以尝试添加一些输出语句,以确定代码执行的正确性,例如在写入数据前后分别打印一些信息,
我本地测试这个代码是没有问题的,你看下是不是你打开错文件了