回答編集履歴
1
処理中に例外が発生してロールバックのコピーに失敗した場合にもテンポラリを削除してしまうのを修正、他
test
CHANGED
@@ -8,19 +8,24 @@
|
|
8
8
|
public class Test {
|
9
9
|
public static void main(String[] args) throws IOException {
|
10
10
|
Path path = Path.of("zzz.txt"); //"c:\\output\\input.txt"
|
11
|
-
Path tmpPath = File.createTempFile("tmp", ".txt")
|
11
|
+
Path tmpPath = Files.createTempFile("tmp", ".txt");
|
12
12
|
Files.copy(path, tmpPath, StandardCopyOption.REPLACE_EXISTING);
|
13
|
-
try(BufferedReader reader = new BufferedReader(new FileReader(tmpPath.toFile()));
|
14
|
-
|
13
|
+
try(PrintWriter writer = new PrintWriter(path.toFile())) {
|
14
|
+
try(BufferedReader reader = Files.newBufferedReader(tmpPath)) {
|
15
|
-
// 置換処理
|
15
|
+
// 置換処理
|
16
|
-
for(String line; (line = reader.readLine()) != null; ) {
|
16
|
+
for(String line; (line = reader.readLine()) != null; ) {
|
17
|
-
writer.println(line.replaceAll("\\?", " "));
|
17
|
+
writer.println(line.replaceAll("\\?", " "));
|
18
|
+
}
|
18
19
|
}
|
20
|
+
try { Files.deleteIfExists(tmpPath); } catch(Exception ignore) {}
|
19
21
|
} catch(Exception e) {
|
22
|
+
try {
|
20
|
-
Files.copy(tmpPath, path, StandardCopyOption.REPLACE_EXISTING); //戻す
|
23
|
+
Files.copy(tmpPath, path, StandardCopyOption.REPLACE_EXISTING); //戻す
|
24
|
+
try { Files.deleteIfExists(tmpPath); } catch(Exception ignore) {}
|
25
|
+
} catch(Exception ee) {
|
26
|
+
System.out.println("rollback error. the original is in " + tmpPath);
|
27
|
+
}
|
21
28
|
throw e;
|
22
|
-
} finally {
|
23
|
-
Files.deleteIfExists(tmpPath);
|
24
29
|
}
|
25
30
|
}
|
26
31
|
}
|