Repository navigation
Expand file tree
/
Copy pathPrefs.java
More file actions
41 lines (39 loc) · 1.71 KB
/
Copy pathPrefs.java
File metadata and controls
41 lines (39 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.nio.file.*;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
// User preferences are stored in files under java.util.prefs.userRoot, which
// FileSystemPreferences locks and chmods as on HotSpot.
public class Prefs {
// Its log lines carry the time; HotSpot logs the same ones. Held here, since
// the log manager keeps loggers weakly and a collected one forgets its level.
static final Logger PREFS_LOG = Logger.getLogger("java.util.prefs");
public static void main(String[] args) throws Exception {
PREFS_LOG.setLevel(Level.OFF);
// a fresh root, not the user's own preferences
Path root = Files.createTempDirectory("prefs");
System.setProperty("java.util.prefs.userRoot", root.toString());
Preferences node = Preferences.userRoot().node("java-web-test");
try {
node.put("greeting", "hello");
node.putInt("count", 3);
node.flush();
node.sync();
System.out.println(node.get("greeting", "?") + " " + node.getInt("count", 0) + " " + String.join(",", node.keys()));
// what reached the backing file, read apart from the cached node
try (var files = Files.walk(root)) {
for (Path f : files.filter(f -> f.endsWith(Path.of("java-web-test", "prefs.xml"))).toList()) {
System.out.println(root.relativize(f));
for (String line : Files.readAllLines(f)) if (line.contains("<entry")) System.out.println(line.strip());
}
}
} finally {
node.removeNode();
Preferences.userRoot().flush();
try (var files = Files.walk(root)) {
files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
}
}