import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Main {
public static void main(String[] args) {
try {
//Get current file system
var fs = FileSystems.getDefault();
var path1 = fs.getPath("./sample.txt");
//File existence confirmation
System.out.println(Files.exists(path1)); //true
//Is the file readable?
System.out.println(Files.isReadable(path1)); //true
//Is the file writable?
System.out.println(Files.isWritable(path1)); //true
//Is the file executable?
System.out.println(Files.isExecutable(path1)); //true
//file size
System.out.println(Files.size(path1));
//File copy
var path2 = Files.copy(path1, fs.getPath("./copy.txt"),
StandardCopyOption.REPLACE_EXISTING);
//Move file
Files.move(path2, fs.getPath("./sub/copy.txt"),
StandardCopyOption.REPLACE_EXISTING);
//File name change
var path3 = Files.move(path1, fs.getPath("./sub/rename.txt"),
StandardCopyOption.REPLACE_EXISTING);
//File deletion
Files.delete(path3);
//Delete if the file exists (no exception occurs)
Files.deleteIfExists(path3);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Main {
public static void main(String[] args) {
try {
var fs = FileSystems.getDefault();
var dir1 = fs.getPath("./playground");
var dir2 = fs.getPath("./data");
//Create folder
Files.createDirectories(dir1);
//Does the folder exist?
System.out.println(Files.exists(dir1)); //true
//Is it a folder?
System.out.println(Files.isDirectory(dir1)); //true
//Subfile under dir2/Get folder stream
var s = Files.list(dir2);
//.Get filename ending in log
s.filter(v -> v.getFileName().toString().endsWith(".log")).
forEach(System.out::println); //./data/test.log
//Folder copy
var dir3 = Files.copy(dir1, fs.getPath("./data"),
StandardCopyOption.REPLACE_EXISTING);
//Move folder
Files.move(dir3, fs.getPath("./data"),
StandardCopyOption.REPLACE_EXISTING);
//Delete folder
Files.delete(fs.getPath("./data/sub"));
//Delete only when the folder exists
Files.deleteIfExists(fs.getPath("./data/sub"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Recommended Posts