File operations
read/write string
// Java 11
Files.writeString(fileName, content);
String content = Files.readString(fileName);
// Java 7
String content = new String (Files.readAllBytes(Paths.get(fileName)));
Files.write(Paths.get(filePath), content.getBytes());
// Java 6
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write(str);
bw.close();
StringBuilder contentBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(fileName))
String line;
while ((line = br.readLine()) != null){
contentBuilder.append(line).append("\n");
}
String content = contentBuilder.toString();
// Java 6 with IO streams
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(content.getBytes());
fos.close();
// on Java 7 you can use Writer/Reader with try-with-resource
try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))){
writer.write(str);
}
deep directory traverse
try (Stream<Path> paths = Files.walk(Paths.get("mydir"))) {
paths.forEach((path)->{
// ... do something
});
} catch (IOException e) {
e.printStackTrace();
}
delete
Following method allows delete file or folder. Folder can be non-empty.
public static void deleteFile(File f) throws IOException {
try(Stream<Path> stream = Files.walk(f.toPath())) {
stream.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
You can replace File.delete() with Files.delete(), which may throw more exceptions.
clean folder
Following method allows to clean folder, without deleting itself.
public static void cleanDir(File dir) throws IOException {
if (dir.isDirectory()) {
try (Stream<Path> stream = Files.walk(dir.toPath())) {
stream.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(f -> {
if (!dir.equals(f)) f.delete();
});
}
}
}
copy files
If you don't need callbacks:
public static void copyFiles(File src, File dst)
throws IOException {
dst.getParentFile().mkdirs();
Files.copy(src.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
Following method allows copy content of one file to another. Code without util classes like Files.
public static boolean copyFiles(File src, File dst,
ProgressListener progressListener,
ErrorHandler errorHandler) {
dst.getParentFile().mkdirs();
long total = src.length();
long current = 0L;
try (InputStream in = new BufferedInputStream(new FileInputStream(src));
OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
current += length;
if (progressListener != null) {
progressListener.onProgress(current, total);
}
}
} catch (Exception e) {
e.printStackTrace();
if (errorHandler != null) {
errorHandler.onError(e);
}
return false;
}
return true;
}