1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender.rolling.action;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.nio.file.Files;
22
23
24
25
26 public class FileRenameAction extends AbstractAction {
27
28
29
30
31 private final File source;
32
33
34
35
36 private final File destination;
37
38
39
40
41 private final boolean renameEmptyFiles;
42
43
44
45
46
47
48
49
50 public FileRenameAction(final File src, final File dst, final boolean renameEmptyFiles) {
51 source = src;
52 destination = dst;
53 this.renameEmptyFiles = renameEmptyFiles;
54 }
55
56
57
58
59
60
61 @Override
62 public boolean execute() {
63 return execute(source, destination, renameEmptyFiles);
64 }
65
66
67
68
69
70
71
72
73
74 public static boolean execute(final File source, final File destination, final boolean renameEmptyFiles) {
75 if (renameEmptyFiles || source.length() > 0) {
76 final File parent = destination.getParentFile();
77 if (parent != null && !parent.exists()) {
78
79
80
81 parent.mkdirs();
82 if (!parent.exists()) {
83 LOGGER.error("Unable to create directory {}", parent.getAbsolutePath());
84 return false;
85 }
86 }
87 try {
88 if (!source.renameTo(destination)) {
89 try {
90 copyFile(source, destination);
91 return source.delete();
92 } catch (final IOException iex) {
93 LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
94 destination.getAbsolutePath(), iex.getMessage());
95 }
96 }
97 return true;
98 } catch (final Exception ex) {
99 try {
100 copyFile(source, destination);
101 return source.delete();
102 } catch (final IOException iex) {
103 LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
104 destination.getAbsolutePath(), iex.getMessage());
105 }
106 }
107 } else {
108 try {
109 source.delete();
110 } catch (final Exception ex) {
111 LOGGER.error("Unable to delete empty file " + source.getAbsolutePath());
112 }
113 }
114
115 return false;
116 }
117
118 private static void copyFile(final File source, final File destination) throws IOException {
119 if (!destination.exists()) {
120 destination.createNewFile();
121 }
122 Files.copy(source.toPath(), destination.toPath());
123 }
124
125 @Override
126 public String toString() {
127 return FileRenameAction.class.getSimpleName() + '[' + source + " to " + destination
128 + ", renameEmptyFiles=" + renameEmptyFiles + ']';
129 }
130 }