简体   繁体   中英

best way to store data in Java like pickle

Basically, I just want to save two integeres into a File, so that i can reuse them the next time the programm starts. Id like to do it like pickle in python, beacuse writing it just into a txt file is cumbersome. I have read some articles and other questions wehere they say I should use Java serializatio or XML or JSON, but Im not sure wheter that is the right thing in my case. Id like to use the easiest way. thank you very much in advance for trying to solve my problem! <3

You could use serialization, XML or JSON (usually with additional libraties). An easy way to store configuration data in files is by using Java property files which are supported by the JRE without any additional dependencies. Property files are text files and have a simple key=value syntax, see below. To write two values to a property file you can do

  String prop1 = "foo";
  String prop2 = "bar";

  try (OutputStream output = new FileOutputStream("config.properties")) {

      Properties prop = new Properties();

      // set the properties value
      prop.setProperty("prop1", prop1);
      prop.setProperty("prop2", prop2);

      // save properties to project root folder
      prop.store(output, "my app's config file");
  } catch (IOException io) {
      io.printStackTrace();
      // TODO: improve error handling
  }

which should give you something like

#my app's config file
#Sat Feb 29 12:29:27 CET 2020
prop2=bar
prop1=foo

And to load it:

try (InputStream input = new FileInputStream("config.properties")) {

Properties prop = new Properties();

// load a properties file
prop.load(input);

// get the property value and print it out
String prop1 = prop.getProperty("prop1");
String prop2 = prop.getProperty("prop2");

System.out.println("prop1 = " + prop1);
System.out.println("prop2 = " + prop2);

} catch (IOException ex) {
  ex.printStackTrace();
  // TODO: improve error handling
}

For integer values you would need some type conversion, eg the first two lines would be

String prop1 = Integer.toString(23);
String prop2 = Integer.toString(42);

and reading the properties then becomes

int prop1 = Integer.parseInt(prop.getProperty("prop1"));
int prop2 = Integer.parseInt(prop.getProperty("prop2"));

This solution does not scale well in case the number of properties increases or there are frequent changes. For a more generic procedure, see this post: Get int, float, boolean and string from Properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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