在Java Properties中,只能直接存儲基本數據類型(如String、int、boolean等)及其字符串表示
在將對象存儲到Properties中之前,您需要將其轉換為字符串。通常,可以使用對象的toString()方法來實現這一點。
例如,假設您有一個名為Person的類:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter 和 Setter 省略
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties properties = new Properties();
Person person = new Person("John", 30);
properties.setProperty("person", person.toString());
// 將Properties保存到文件
try {
properties.store(new FileOutputStream("config.properties"), null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties properties = new Properties();
try {
// 從文件加載Properties
properties.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String personString = properties.getProperty("person");
System.out.println("Person from properties: " + personString);
// 將字符串轉換回原始對象
Person person = parsePerson(personString);
System.out.println("Parsed Person: " + person.getName() + ", " + person.getAge());
}
private static Person parsePerson(String personString) {
String[] parts = personString.substring(personString.indexOf('{') + 1, personString.lastIndexOf('}')).split(", ");
String name = parts[0].substring(parts[0].indexOf("'") + 1, parts[0].lastIndexOf("'"));
int age = Integer.parseInt(parts[1]);
return new Person(name, age);
}
}
這個示例演示了如何將復雜數據類型轉換為字符串并存儲到Java Properties中,以及如何從Properties中讀取字符串并將其轉換回原始數據類型。注意,這種方法可能不適用于所有復雜數據類型,您可能需要根據您的需求調整轉換邏輯。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。