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.helper;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.nio.channels.FileChannel;
24
25
26
27
28 public class FileRenameAction extends AbstractAction {
29
30
31
32
33 private final File source;
34
35
36
37
38 private final File destination;
39
40
41
42
43 private final boolean renameEmptyFiles;
44
45
46
47
48
49
50
51
52 public FileRenameAction(final File src, final File dst, final boolean renameEmptyFiles) {
53 source = src;
54 destination = dst;
55 this.renameEmptyFiles = renameEmptyFiles;
56 }
57
58
59
60
61
62
63 @Override
64 public boolean execute() {
65 return execute(source, destination, renameEmptyFiles);
66 }
67
68
69
70
71
72
73
74
75
76 public static boolean execute(final File source, final File destination, final boolean renameEmptyFiles) {
77 if (renameEmptyFiles || source.length() > 0) {
78 final File parent = destination.getParentFile();
79 if (parent != null && !parent.exists()) {
80 if (!parent.mkdirs()) {
81 LOGGER.error("Unable to create directory {}", parent.getAbsolutePath());
82 return false;
83 }
84 }
85 try {
86 if (!source.renameTo(destination)) {
87 try {
88 copyFile(source, destination);
89 return source.delete();
90 } catch (final IOException iex) {
91 LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
92 destination.getAbsolutePath(), iex.getMessage());
93 }
94 }
95 return true;
96 } catch (final Exception ex) {
97 try {
98 copyFile(source, destination);
99 return source.delete();
100 } catch (final IOException iex) {
101 LOGGER.error("Unable to rename file {} to {} - {}", source.getAbsolutePath(),
102 destination.getAbsolutePath(), iex.getMessage());
103 }
104 }
105 } else {
106 try {
107 source.delete();
108 } catch (Exception ex) {
109 LOGGER.error("Unable to delete empty file " + source.getAbsolutePath());
110 }
111 }
112
113 return false;
114 }
115
116 private static void copyFile(final File source, final File destination) throws IOException {
117 if (!destination.exists()) {
118 destination.createNewFile();
119 }
120
121 FileChannel srcChannel = null;
122 FileChannel destChannel = null;
123 FileInputStream srcStream = null;
124 FileOutputStream destStream = null;
125 try {
126 srcStream = new FileInputStream(source);
127 destStream = new FileOutputStream(destination);
128 srcChannel = srcStream.getChannel();
129 destChannel = destStream.getChannel();
130 destChannel.transferFrom(srcChannel, 0, srcChannel.size());
131 } finally {
132 if (srcChannel != null) {
133 srcChannel.close();
134 }
135 if (srcStream != null) {
136 srcStream.close();
137 }
138 if (destChannel != null) {
139 destChannel.close();
140 }
141 if (destStream != null) {
142 destStream.close();
143 }
144 }
145 }
146 }