Slide 1

Slide 1 text

Properties API Jussi Pohjolainen

Slide 2

Slide 2 text

To store preferences • Simple API to • fetch • store • key value pairs

Slide 3

Slide 3 text

import java.io.*; import java.util.*; class Main { public static void main(String [] args) throws Exception { Properties prop = new Properties(); // set key and value prop.setProperty("fontSize", "24"); prop.setProperty("fontColor", "RGB(255,255,255)"); String optionalComments = "My preferences file"; prop.store(new FileWriter("./myfile.prop"), optionalComments); } }

Slide 4

Slide 4 text

myfile.prop #My preferences file #Sun Apr 26 10:56:55 EEST 2020 fontSize=24 fontColor=RGB(255,255,255)

Slide 5

Slide 5 text

Reading import java.io.*; import java.util.*; class Main { public static void main(String [] args) throws Exception { Properties prop = new Properties(); prop.load(new FileReader("./myfile.prop")); System.out.println(prop.get("fontSize")); System.out.println(prop.get("fontColor")); } }

Slide 6

Slide 6 text

Storing XML import java.io.*; import java.util.*; class Main { public static void main(String [] args) throws Exception { Properties prop = new Properties(); // set key and value prop.setProperty("fontSize", "24"); prop.setProperty("fontColor", "RGB(255,255,255)"); String optionalComments = "My preferences file"; prop.storeToXML(new FileOutputStream("./myfile.xml"), optionalComments); } }

Slide 7

Slide 7 text

myfile.xml My preferences file 24 RGB(255,255,255)

Slide 8

Slide 8 text

Reading import java.io.*; import java.util.*; class Main { public static void main(String [] args) throws Exception { Properties prop = new Properties(); prop.loadFromXML(new FileInputStream("./myfile.xml")); System.out.println(prop.getProperty("fontSize")); System.out.println(prop.getProperty("fontColor")); } }

Slide 9

Slide 9 text

Jackson

Slide 10

Slide 10 text

Jackson • Java classes to json mapping • External class library, add dependency • You can use Jackson to save for example preferences file

Slide 11

Slide 11 text

Dependency com.fasterxml.jackson.core jackson-databind 2.10.3

Slide 12

Slide 12 text

Pojo public class Dog { private String name; public void setName(String name) { this.name = name; } public String getName() { return this.name; } }

Slide 13

Slide 13 text

Main import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; class Main { public static void main(String [] args) throws Exception { Dog spot = new Dog(); spot.setName("Spot"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(new File("./file.json"), spot); Dog temp = objectMapper.readValue(new File("./file.json"), Dog.class); System.out.println(temp.getName()); } }