您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。