javaNIO 学习笔记(五)

javaNIO 学习笔记(五)

本片大多数内容大多都是翻译参考文档。

file(java.nio.file.Files)

Java NIO文件类提供了几种在文件系统中操作文件的方法

// 检查文件系统中是否存在给定路径
Files.exists(Path path, LinkOption... options)
// 若创建的目录存在会抛异常 FileAlreadyExistsException 
Files.createDirectory(Path path)
// 如果目标文件已经存在抛出FileAlreadyExistsException如果要将文件复制到的目录不存在,就会抛出IOException
Files.copy()
// 覆盖现有的文件    
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);  
// 将文件从一个路径移动到另一个路径
Files.move()
Files.delete()    
// 遍历  path目录,操作接口    
Files.walkFileTree(Path,FileVisitor)    
    FileVisitor里面的方法都是返回一个FileVisitResult(枚举)
        CONTINUE 继续
        TERMINATE 终止:文件遍历现在应该终止
        SKIP_SIBLING 跳过同级 :文件遍历应该继续,但不需要访问该文件或目录的任何同级
        SKIP_SUBTREE 跳过子级:文件遍历应该继续,但是不需要访问这个目录中的子目录
package jniolearn;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: jimmy
 * @Date: 2020/6/16 00:29
 * @Description:
 */
public class FilePrc {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        //将传统io读写文件高度封装之后,在NIO.2中拷贝文件只需要调用File工具类的copy()方法
        Files.copy(Paths.get("tmp.txt"), new FileOutputStream("tmp2.txt"));
        //是否为隐藏文件
        System.out.println("tmp.txt是否为隐藏文件: "+Files.isHidden(Paths.get("tmp.txt")));
        //一次性读取所有行 , 需要指定编码规则
        List<String> lines = Files.readAllLines(Paths.get("tmp.txt"), Charset.forName("gbk"));
        System.out.println(lines);
        //文件大小
        System.out.println("tmp.txt文件大小为: "+Files.size(Paths.get("tmp.txt")));
        List<String> poem = new ArrayList<>();
        poem.add("海阔凭鱼跃");
        poem.add("天高任鸟飞");
        //直接将字符串数组写入文件
        Files.write(Paths.get("tmp.txt"), poem, Charset.forName("gbk"));
    }
}

AsynchronousFileChannel

AsynchronousFileChannel是Java 7中添加的

Path path = Paths.get("data/test.xml");
// 第一个参数是指向与AsynchronousFileChannel相关联的文件的Path实例
// 第二个参数是一个或多个打开选项
AsynchronousFileChannel fileChannel =
    AsynchronousFileChannel.open(path, StandardOpenOption.READ);

读取数据

  • Future
AsynchronousFileChannel fileChannel = 
    AsynchronousFileChannel.open(path, StandardOpenOption.READ);

ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;

Future<Integer> operation = fileChannel.read(buffer, position);

while(!operation.isDone());

buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data));
buffer.clear();
  • CompletionHandler
fileChannel.read(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() {
    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        System.out.println("result = " + result);

        attachment.flip();
        byte[] data = new byte[attachment.limit()];
        attachment.get(data);
        System.out.println(new String(data));
        attachment.clear();
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {

    }
});

一旦读取操作完成,将调用CompletionHandlercompleted()方法。对于completed()方法的参数传递一个整数,它告诉我们读取了多少字节,以及传递给read()方法的“附件”。“附件”是read()方法的第三个参数。在本例中,它是ByteBuffer,数据也被读取。如果读取操作失败,则将调用CompletionHandlerfailed()方法。

写数据

  • Future
Path path = Paths.get("data/test-write.txt");
AsynchronousFileChannel fileChannel = 
    AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);

ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;

buffer.put("test data".getBytes());
buffer.flip();

Future<Integer> operation = fileChannel.write(buffer, position);
buffer.clear();

while(!operation.isDone());

System.out.println("Write done");
  • CompletionHandler
Path path = Paths.get("data/test-write.txt");
if(!Files.exists(path)){
    Files.createFile(path);
}
AsynchronousFileChannel fileChannel = 
    AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);

ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;

buffer.put("test data".getBytes());
buffer.flip();

fileChannel.write(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() {

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        System.out.println("bytes written: " + result);
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.out.println("Write failed");
        exc.printStackTrace();
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章