Почитал википедию
возможно, что-то не учел:
варианты резделителя: ":", " : ", "=", " = "
экранирование пробела в ключе: "\ "
игнорирование комментариев и пустых строк (ну, по идее пустые строки нужно игнорировать)
обратный слеш в конце строки (нужно для парсинга)
символы \n, \r и \t -- насколько я понял, в распарсенном виде превращаются в настоящие конец строки, табуляцию и возврат карретки. Но при сохранении строк с этими символами -- мы должны их экранировать и сохранять
юникоды учел -- я их просто отображаю / сохраняю как есть
Подскажите, пожалуй
package com.javarush.task.task20.task2003;
import javax.swing.text.Style;
import java.io.*;
import java.util.*;
/*
Знакомство с properties
*/
public class Solution {
public static Map<String, String> properties = new HashMap<>();
public static void main(String[] args) throws Exception {
Solution sl = new Solution();
sl.fillInPropertiesMap();
System.out.println(properties);
}
public void fillInPropertiesMap() throws Exception {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String fileName = r.readLine();
r.close();
// String fileName = "/home/vasily/hello.txt";
// properties.put("website", "https://ru.wikipedia.org/");
// properties.put("message", "Добро пожаловать в \\nВикипедию!");
// properties.put("some unicode", "\\u0009");
FileInputStream inputStream = new FileInputStream(fileName);
load(inputStream);
inputStream.close();
// System.out.println(properties);
FileOutputStream outputStream = new FileOutputStream(fileName);
save(outputStream);
outputStream.close();
}
public void save(OutputStream outputStream) throws Exception {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
for (Map.Entry<String, String> entry : properties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
key = sanitizeSaveKey(key);
value = sanitizeSaveValue(value);
writer.write(key + "=" + value);
writer.newLine();
writer.flush();
}
}
public void load(InputStream inputStream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String tempKey = null;
StringBuilder tempValue = new StringBuilder();
while (reader.ready()) {
String line = reader.readLine();
if (line.isEmpty()) continue;
if (line.startsWith("#") || line.startsWith("!")) continue;
if (tempKey != null) {
String value = leftTrim(line);
value = sanitizeLoadValue(value);
if (value.endsWith("\\")) {
tempValue.append(value, 0, value.length() - 1);
continue;
}
tempValue.append(value);
properties.put(tempKey, tempValue.toString());
tempKey = null;
tempValue = new StringBuilder();
continue;
}
String key = parseKey(line);
String value = parseValue(line);
key = sanitizeLoadKey(key);
value = sanitizeLoadValue(value);
if (value.endsWith("\\")) {
tempKey = key;
tempValue.append(value, 0, value.length() - 1);
} else {
properties.put(key, value);
tempKey = null;
tempValue = new StringBuilder();
}
}
if (tempKey != null) properties.put(tempKey, tempValue.toString());
reader.close();
}
public static String leftTrim(String string)
{
return string.replaceAll("^\\s+", "");
}
public static String parseKey(String line)
{
String[] keyPart = line.split(" ?[:=] ?");
return keyPart[0];
}
public static String parseValue(String line)
{
String[] valuePart = line.split("^.*? ?[:=] ?");
return valuePart.length == 2 ? valuePart[1] : "";
}
public static String sanitizeSaveKey(String key)
{
return key
.replaceAll(" ", "\\\\ ")
.replaceAll("=", "\\\\=")
.replaceAll(":", "\\\\:")
;
}
public static String sanitizeSaveValue(String value)
{
return value
.replaceAll(System.lineSeparator(), "\\\\" + System.lineSeparator())
.replaceAll("\r", "\\\\r")
.replaceAll("\t", "\\\\t")
;
}
public static String sanitizeLoadKey(String key)
{
return key
.replaceAll("\\\\ ", " ")
.replaceAll("\\\\:", ":")
.replaceAll("\\\\=", "=")
;
}
public static String sanitizeLoadValue(String value)
{
return value
.replaceAll("\\\\" + System.lineSeparator(), System.lineSeparator())
.replaceAll("\\\\r", "\r")
.replaceAll("\\\\t", "\t")
;
}
}