how to write into a text file in Java

前端 未结 5 1452
南旧
南旧 2021-01-27 01:35

I am doing a project in java and in that i need to add and modify my text file at runtime,which is grouped in the jar.

I am using class.getResourceAsStream(filename) thi

5条回答
  •  情书的邮戳
    2021-01-27 01:53

    A good solution that avoids the need to put your items into a Jar file is to read (if present) a properties file out of a hidden subdirectory in the user's home directory. The logic looks a bit like this:

    if (the hidden directory named after my application doesn't exist) {
      makeTheHiddenDirectory();
      writeTheDefaultPropertiesFile();
    }
    Properties appProps = new Properties();
    appProps.load(new FileInputStream(fileInHiddenDir));
    ...
    ... After the appProps have changed ...
    ...
    appProps.store(new FileOutputStream(fileInHiddenDir), "Do not modify this file");
    

    Look to java.util.Properties, and keep in mind that they have two different load and store formats (key = value based and XML based). Pick the one that suits you best.

提交回复
热议问题