-
Notifications
You must be signed in to change notification settings - Fork 185
/
FileUtils.java
250 lines (232 loc) · 8.19 KB
/
FileUtils.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.common.util;
import org.apache.commons.collections.buffer.CircularFifoBuffer;
import org.apache.commons.io.LineIterator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jfree.io.IOUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.util.Set;
/**
* Simple file utilities to read/write strings to a file on disk.
*
*/
public class FileUtils {
private static Logger log = LogManager.getLogger(FileUtils.class);
private FileUtils() {
}
/**
* Save a String to a file on disk using specified path.
*
* WARNING: This deletes the original file before it writes.
*
* @param contents to save to file on disk
* @param path to save file to.
*/
public static void writeStringToFile(String contents, String path) {
try {
File file = new File(path);
if (file.exists()) {
file.delete();
}
file.createNewFile();
try (FileOutputStream fos = new FileOutputStream(file);
FileWriter fw = new FileWriter(fos.getFD());
BufferedWriter output = new BufferedWriter(fw)) {
output.write(contents);
output.flush();
fw.flush();
fos.getFD().sync();
}
}
catch (Exception e) {
log.error("Error trying to write file to disk: [{}]", path, e);
throw new RuntimeException(e);
}
}
/**
* convenient method to set user/group and permissions of a file in one go.
*
* @param path path to file
* @param user username
* @param group groupname
* @param permissions set of permissions
* @throws IOException when any of the file operations fail
*/
public static void setAttributes(Path path, String user, String group, Set<PosixFilePermission> permissions)
throws IOException {
FileSystem fileSystem = FileSystems.getDefault();
UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
PosixFileAttributeView view = Files.getFileAttributeView(
path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
view.setOwner(service.lookupPrincipalByName(user));
view.setGroup(service.lookupPrincipalByGroupName(group));
view.setPermissions(permissions);
}
/**
* Read a file off disk into a String and return it.
*
* Expect weird stuff if the file is not textual.
*
* @param path of file to read in
* @return String containing file.
*/
public static String readStringFromFile(String path) {
return readStringFromFile(path, false);
}
/**
* Read a file off disk into a String and return it.
*
* Expect weird stuff if the file is not textual.
*
* @param path of file to read in
* @param noLog don't log the content of the file
* @return String containing file.
*/
public static String readStringFromFile(String path, boolean noLog) {
if (log.isDebugEnabled()) {
log.debug("readStringFromFile: {}", StringUtil.sanitizeLogInput(path));
}
File f = new File(path);
BufferedReader input;
try {
input = new BufferedReader(new FileReader(f));
StringWriter writer = new StringWriter();
IOUtils.getInstance().copyWriter(input, writer);
String contents = writer.toString();
if (noLog && log.isDebugEnabled()) {
log.debug("contents: {}", contents);
}
return contents;
}
catch (FileNotFoundException e) {
throw new RuntimeException("File not found: " + path);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Read a file off disk into a byte array with specified range
*
* This can use lots of memory if you read a large file
*
* @param fileToRead File to read part of into byte array
* @param start index of read
* @param end index of read
* @return byte[] array from file.
*/
public static byte[] readByteArrayFromFile(File fileToRead, long start, long end) {
log.debug("readByteArrayFromFile: {} start: {} end: {}", fileToRead.getAbsolutePath(), start, end);
int size = (int) (end - start);
log.debug("size of array: {}", size);
// Create the byte array to hold the data
byte[] bytes = new byte[size];
InputStream is = null;
try {
is = new FileInputStream(fileToRead);
// Read in the bytes
int offset = 0;
int numRead = 0;
// Skip ahead
is.skip(start);
// start reading
while (offset < bytes.length &&
(numRead) >= 0) {
numRead = is.read(bytes, offset,
bytes.length - offset);
offset += numRead;
}
}
catch (IOException fnf) {
log.error("Could not read from: {}", fileToRead.getAbsolutePath());
throw new RuntimeException(fnf);
}
finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return bytes;
}
/**
* Reads and returns the last n lines from a given file as string.
* @param pathToFile path to file
* @param lines size of the tail
* @return tail of file as string
*/
public static String getTailOfFile(String pathToFile, Integer lines) {
InputStream fileStream = null;
CircularFifoBuffer buffer = new CircularFifoBuffer(lines);
try {
fileStream = new FileInputStream(pathToFile);
LineIterator it = org.apache.commons.io.IOUtils.lineIterator(fileStream,
(String) null);
while (it.hasNext()) {
buffer.add(it.nextLine());
}
}
catch (FileNotFoundException e) {
log.error("File not found: {}", pathToFile);
throw new RuntimeException(e);
}
finally {
org.apache.commons.io.IOUtils.closeQuietly(fileStream);
}
// Construct a string from the buffered lines
StringBuilder sb = new StringBuilder();
for (Object s : buffer) {
sb.append(s);
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
/**
* Delete file with a given path.
* @param path path of the file to be deleted
*/
public static void deleteFile(Path path) {
try {
Files.deleteIfExists(path);
}
catch (IOException e) {
log.warn("Could not delete file: {}", path, e);
}
}
}