Netty file programming
Directory
- Netty file programming
- 1. FileChannel
-
- 1. Obtaining method
- 2. Reading method
- 3. Writing method
- 4. Close method
- 5. Location method
- 6. Size method
- 7. Forced writing method
- 2. Two Channels transmit data
- 3. Path
- 4. Files
-
- 1. Check if the file exists
- 2.Create a directory
- 3.Copy files
- 4. Move files
- 5. Delete files/directories
- 6. Traverse directory files
- 7. Delete multi-level directories
- 8. Copy multi-level directories
1. FileChannel
FileChannel only works in blocking mode
1. Obtaining method
FileChannel cannot be opened directly. FileChannel must be obtained through the following methods. They all have getChannel methods.
The code is as follows (example):
/* * The channel obtained through FileInputStream can only be read */ try {<!-- --> FileInputStream fileInputStream = new FileInputStream("test.txt"); FileChannel channel = fileInputStream.getChannel(); } catch (IOException e) {<!-- --> e.printStackTrace(); } /* * The channel obtained through FileOutputStream can only be written */ try {<!-- --> FileOutputStream fileOutputStream = new FileOutputStream("test.txt"); FileChannel channel = fileOutputStream.getChannel(); } catch (IOException e) {<!-- --> e.printStackTrace(); } /* * Whether it can be read and written through RandomAccessFile is determined by the read and write mode when constructing RandomAccessFile. */ try (FileChannel channel = new RandomAccessFile("test.txt", "r").getChannel()){<!-- --> } catch (IOException e) {<!-- --> e.printStackTrace(); }
2. Reading method
The code is as follows (example):
int bytes = channel.read(buffer);
3. Writing method
The code is as follows (example):
channel.write(buffer);
Tips: The channel.write() method cannot write all the contents of the buffer to the channel at one time
4. Close method
The channel must be closed, but calling the close method of FileInputStream, FileOutputStream, and RandomAccessFile will indirectly call the close method.
5. Position method
The code is as follows (example):
//Get the current location long position = channel.position(); //Set current location long newPos = 3; channel.position(newPos);
If the current position is set to the end of the file, -1 will be returned when reading. At this time, writing will append content, but if the position exceeds the end of the file, there will be a hole (00) between the end of the original content and the beginning of the new content when writing again.
6. Size method
The code is as follows (example):
long size = channel.size();
7. Forced writing method
For performance reasons, the operating system will cache the data and write it to disk immediately. You can call the focus(teue) method to write the file content and metadata (file permissions and other information to the disk immediately)
2. Two Channels transmit data
The code is as follows (example):
public static void main(String[] args) {<!-- --> try {<!-- --> FileChannel from = new FileInputStream("data.txt").getChannel(); FileChannel to = new FileInputStream("to.txt").getChannel(); /* * transferTo() is highly efficient. The bottom layer will use the operating system's zero copy for optimization, but it can only transfer up to 2G of data. * position: starting position, count: amount of data transferred, target: current position */ from.transferTo(0, from.size(), to); /* *Solution to the problem that only 2G can be transmitted */ for (long i = from.size(); i > 0; ) {<!-- --> i -= from.transferTo((from.size() - i), from.size(), to); } } catch (IOException e) {<!-- --> e.printStackTrace(); } }
3. Path
jdk7 introduced the Path and Paths classes
- Path represents the file path
- Path represents a tool class used to obtain Path instances
- .represents the current path,…represents the upper-level path
public static void main(String[] args) {<!-- --> Path path = Paths.get("data.txt"); //Relative path, use user.dir environment variable to locate data.txt Path path1 = Paths.get("d:\data.txt"); //Absolute path represents d:\data.txt Path path2 = Paths.get("d:/data.txt"); //Absolute path represents d:\data.txt Path path3 = Paths.get("d:\data","project"); //Represents d:\data\project }
4. Files
1. Check whether the file exists
The code is as follows (example):
Path path = Paths.get("data.txt"); System.out.println(Files.exists(path));
2. Create directory
The code is as follows (example):
public static void main(String[] args) {<!-- --> try {<!-- --> /* * Create a first-level directory * If the directory exists, an exception FileAlreadyExistsException will be thrown * You cannot create multiple levels of directories at one time, otherwise NoSuchFileException will be thrown */ Files.createDirectory(Paths.get("hello/data")); /* * Create multi-level directories */ Files.createDirectory(Paths.get("hello/data/paths")); } catch (IOException e) {<!-- --> e.printStackTrace(); } }
3. Copy files
The code is as follows (example):
public static void main(String[] args) {<!-- --> try {<!-- --> Path source = Paths.get("hello/data.txt"); Path target = Paths.get("hello/target.txt"); /* * If the file already exists, an exception FileAlreadyExistsException will be thrown. * If you want to use source to overwrite target, you need to use StandardCopyOption to control it. */ Files.copy(source,target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) {<!-- --> e.printStackTrace(); } }
4.Move files
The code is as follows (example):
public static void main(String[] args) {<!-- --> try {<!-- --> Path source = Paths.get("hello/data.txt"); Path target = Paths.get("hello/target.txt"); /* * StandardCopyOption.ATOMIC_MOVE ensures atomicity of file movement */ Files.copy(source,target, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) {<!-- --> e.printStackTrace(); } }
5. Delete files/directories
The code is as follows (example):
public static void main(String[] args) {<!-- --> try {<!-- --> /* * Delete Files */ Path source = Paths.get("hello/data.txt"); Files.delete(source); // If the file does not exist, NoSuchFileException will be thrown /* * Delete directories, only empty directories can be deleted */ Path target = Paths.get("hello/data"); Files.delete(target); // If the directory contains content, an exception DirectoryNotEmptyException will be thrown } catch (IOException e) {<!-- --> e.printStackTrace(); } }
6. Traverse directory files
The code is as follows (example):
public static void main(String[] args) throws IOException {<!-- --> // Count the total number of files AtomicInteger dirCount = new AtomicInteger(); AtomicInteger fileCount = new AtomicInteger(); // Visitor mode Files.walkFileTree(Paths.get("E:\environment\java"), new SimpleFileVisitor<Path>() {<!-- --> @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {<!-- --> System.out.println("Folder----------》" + dir); dirCount.incrementAndGet(); return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {<!-- --> System.out.println("File----------》" + file); fileCount.incrementAndGet(); return super.visitFile(file, attrs); } }); System.out.println("Number of folders:" + dirCount); System.out.println("Number of files" + fileCount); }
Find the code example of the specified jar file:
public static void main(String[] args) throws IOException {<!-- --> // Total statistics AtomicInteger jarCount = new AtomicInteger(); Files.walkFileTree(Paths.get("E:\environment\java"), new SimpleFileVisitor<Path>() {<!-- --> @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {<!-- --> if (file.toString().endsWith(".jar")) {<!-- --> System.out.println("File----------》" + file); } jarCount.incrementAndGet(); return super.visitFile(file, attrs); } }); System.out.println("Number of jar packages:" + jarCount); }
7. Delete multi-level directories
The code is as follows (example): (dangerous code)
public static void main(String[] args) throws IOException {<!-- --> Files.walkFileTree(Paths.get("E:\environment\java"), new SimpleFileVisitor<Path>() {<!-- --> @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {<!-- --> System.out.println("Enter file----->" + dir); return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {<!-- --> System.out.println("The file is-------->" + file); Files.delete(file); return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {<!-- --> Files.delete(dir); System.out.println("----->Exit file" + dir); return super.postVisitDirectory(dir, exc); } }); }
8. Copy multi-level directories
The code is as follows (example):
public static void main(String[] args) throws IOException {<!-- --> String source = "E:\environment\java"; String target = "D:\data\java"; Files.walk(Paths.get(source)).forEach(path -> {<!-- --> try {<!-- --> String targetName = path.toString().replace(source, target); //is a directory if (Files.isDirectory(path)) {<!-- --> Files.createDirectory(Paths.get(targetName)); }else if (Files.isRegularFile(path)){<!-- --> // is a file Files.copy(path,Paths.get(targetName)); } } catch (Exception e) {<!-- --> e.printStackTrace(); } }); }