File Operations in Java
1). Check if the file exists in Java
Path path = Paths.get("H:\\temp\\hello.pdf");
public static boolean exists(final Path path) {
return path == null ? false : Files.exists(path);
}
2). Read File bytes
public static byte[] read(final Path path) throws IOException {
if (Files.exists(path)) {
return Files.readAllBytes(path);
} else {
throw new IOException("Unable to find file to read " + path);
}
}
3). Move the file to other location
Path src = Paths.get("H:\\temp\\hello");
Path dest = Paths.get("H:\\temp\\bye");
public static void move(final Path src, final Path dest) throws IOException {
Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);
}
4). Get all files in given path
getFilesFromFolder(folder, "*");
public static List<Path> getFolders(final Path folder, final String glob) {
final List<Path> files = new ArrayList<Path>();
if (Files.exists(folder)) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder, glob)) {
for (final Path entry : stream) {
if (Files.isDirectory(entry)) {
System.out.println("Util scanner found folder : " + entry.getFileName());
files.add(entry);
}
}
} catch (final IOException e) {
System.out.println("Util scanner error during search folder "+ e);
}
} else {
System.out.println("Util scanner, root does not exist " + folder);
}
return files;
}
5). Get all files from given folder path with given file name text
public static Map<String, List<Path>> getFilesFromFolders(final Path rootFolder, final String glob) {
final Map<String, List<Path>> filesFromFolders = new LinkedHashMap<String, List<Path>>();
final List<Path> folders = getFolders(rootFolder);
for (final Path folder : folders) {
final List<Path> files = getFilesFromFolder(folder, empty(glob) ? "*" : glob);
if (exists(files)) {
final String key = folder.getFileName().toString();
filesFromFolders.put(key, new ArrayList<Path>());
for (final Path file : files) {
filesFromFolders.get(key).add(file);
}
}
}
return filesFromFolders;
}
6). Delete all files from given path with given extension
public static void deleteAllWithExt(final Path folder, final String extension) throws IOException {
if (Files.exists(folder)) {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(final Path arg0, final IOException arg1) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
System.out.println("Delete file " + folder);
if (file.toString().toUpperCase().endsWith(extension.toUpperCase())) {
Files.delete(file);
}
return FileVisitResult.CONTINUE;
}
});
} else {
System.out.println("Try to delete non existing directory " + folder);
}
}
7). Delete all files from given path
public static void deleteAll(final Path folder) throws IOException {
if (Files.exists(folder)) {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(final Path arg0, final IOException arg1) throws IOException {
System.out.println("Delete folder " + folder);
Files.delete(arg0);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
System.out.println("Delete file " + folder);
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
} else {
System.out.println("Try to delete non existing directory " + folder);
}
}
8). How to get the type of a file in java?
9). Rename file to new Name
public static void renameToNewfile(File srcFile,String localFolderName)
throws IOException {
String currentVersion = localFolderName+File.separator+srcFile.getName();
boolean renamed = srcFile.renameTo(new File(currentVersion));
System.out.println(srcFile.getName() + " renamed to -> " + renamed);
}
10). Rename all files in given folder
public static void renameLocalFilesInDir(String localFolderName) throws Exception {
//renameLocalFilesInDir("H:\\temp\\hello");
File srcDir = new File(localFolderName);
File backup = new File(srcDir.getAbsolutePath()+File.separator+"backup");
backup.mkdir();
for (File srcFile : srcDir.listFiles()) {
if (srcFile.isDirectory()) {
recursiveFilesRename(srcFile.listFiles(), 0,backup.getAbsolutePath());
} else {
renameToNewfile(srcFile,backup.getAbsolutePath());
}
}
}
public static void recursiveFilesRename(File[] fileArray, int level,
String localFolderName) throws Exception {
for (File srcFile : fileArray) {
if (srcFile.isFile()) {
renameToNewfile(srcFile,localFolderName);
} else if (srcFile.isDirectory()) {
recursiveFilesRename(srcFile.listFiles(), level + 1,
localFolderName);
}
}
}
11). Replace text inside file in java
How to read data from a file in java?
public static void replace(final Path path, final String regex, final String text) throws IOException {
String file = new String(Files.readAllBytes(Paths.get("file.txt")));
file = file.replaceAll(regex, text);
Files.write(path, file.getBytes());
}
12). How to read a file and write to another file in java?
public static void readWriteInFile() throws IOException {
String fileText = new String(Files.readAllBytes(Paths.get(""H:\\temp\\file.txt")));
Path path = Paths.get("H:\\temp\\hello.txt");
Files.write(path, fileText.getBytes());
}
13). How to write a string to a file in java?
public static void writeStringInFile() throws IOException {
String textString ="Hello World!!!";
Path path = Paths.get("H:\\temp\\hello.txt");
Files.write(path, textString.getBytes());
}
In this article, we have seen File Operations in Java
0 Comments
Post a Comment