Я хочу использовать предварительно сконфигурированные свойства File
, загрузить его и после этого добавить строку под уже существующей строкой по умолчанию config.properties
.Свойства Файл Java
У меня есть read()
функцию, которая будет читать/загрузить мой файл по умолчанию Properties
и у меня есть write()
функцию, которая будет добавлять String key = "hey"; String value = "ho";
Но когда я запускаю read()
и write()
и когда я смотрю в новом config.properties
я только вижу
hey=ho
В моем стандартном config.properties я получил
ha=hi
hu=hu
Но я хочу в моей новой конфигурации:
ha=hi
hu=hu
hey=ho
Мой код:
Properties prop = new Properties();
public static PropertiesIParse instance;
public PropertiesIParse() {
instance = this;
}
public PropertiesIParse getInstance() {
return instance;
}
public Properties getProp() {
return prop;
}
public void read() {
InputStream input = null;
try {
String filename = "/config.properties";
input = PropertiesIParse.class.getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
getProp().load(input);
Enumeration<?> e = getProp().propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = getProp().getProperty(key);
System.out.println("KeyKey : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void write() {
String filename = "config.properties";
FileOutputStream out;
//prop = new Properties();
String key = "hey";
String value = "ho";
try {
out = new FileOutputStream(filename, true);
getProp().setProperty(key, value);
getProp().store(out, "--type--"); // <---- variable pour dire YYYY MM DD etc.
out.close();
} catch (IOException i) {
System.out.println("Probleme avec l'écriture dans le fichier Property." + i.getMessage());
i.printStackTrace();
}
}
Итак, в моем главном методе:
new PropertiesIParse().getInstance().read();
new PropertiesIParse().getInstance().write();
EDIT
я изменить то, что вы говорите, но я получил то же самое ... новый config.properties только с моим prop.store (k еу, значение) в нем
Properties prop = new Properties();
static PropertiesIParse instance;
private PropertiesIParse() {
instance = this;
}
public static PropertiesIParse getInstance() {
if (instance== null) {
instance = new PropertiesIParse();
}
return instance;
}
public void read() {
InputStream input = null;
Properties prop = new Properties();
try {
String filename = "config.properties";
input = PropertiesIParse.class.getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value =prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void write(String key, String value) {
Properties prop = new Properties();
String filename = "./config.properties";
String comment="";
FileOutputStream out;
try {
out = new FileOutputStream(filename, true);
prop.setProperty(key, value);
prop.store(out, "-"+key+"-"+comment);
out.close();
} catch (IOException i) {
System.out.println("Probleme avec l'écriture dans le fichier Property." + i.getMessage());
i.printStackTrace();
}
}
Мой главный
PropertiesIParse.getInstance().read();
PropertiesIParse.getInstance().write(new String("ok"),new String("iiiii"));
И я получил только ок = IIIII в нем ... я, конечно, пропустить что-то там, спасибо за вашу помощь
Или начать с не ленивым одноточечным. Гораздо меньше хлопот. – Fildor
Спасибо за ваш ответ, см. Мое редактирование. –
В вашем редактировании вы также добавили 'Свойство prop = new Properties();' в свои методы. Таким образом, prop всегда будет пустым, если вы добавите новые значения. Удалите эти строки, и он должен работать. – Frank