7天掌握NIO和SOCKET,第四天,通道打开文件的StandardOpenOption的枚举常量的使用方法,判断通道是否打开

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class test_06 {
    public static void main(String[] args) throws Exception {
        //打开一个文件

        //1:枚举常量:CREATE和WRITE
        //1.1:只使用CREATE
        //method_01();
    private static void method_01() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\aaa.txt");
        FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.CREATE);
        fileChannel.close();
        //只是用CREADTE则报错:Exception in thread "main" java.nio.file.NoSuchFileException: C:\Users\10167\Desktop\aaa.txt
    }
        //1.2:同时使用CREATE和WRITE
        //method_02();

    private static void method_02() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\aaa.txt");
        Path path = file.toPath();
        FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.CREATE,StandardOpenOption.WRITE);
        fileChannel.close();
        //创建成功,桌面上出现aaa.txt
    }
        //2:枚举常量:APPEND:在文件末尾继续插入
        //method_03();

    private static void method_03() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\test.txt");
        Path path = file.toPath();
        FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.APPEND);
        fileChannel.write(ByteBuffer.wrap("你好".getBytes()));
        fileChannel.close();
        //源文件:abcde,执行后:abcde你好
    }
        //3:枚举常量:READ,以读的方式打开文件
        //method_04();

    private static void method_04() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\test.txt");
        Path path = file.toPath();
        FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.READ);
        ByteBuffer byteBuffer = ByteBuffer.allocate(50);
        fileChannel.read(byteBuffer);
        byteBuffer.position(0);
        CharBuffer charBuffer = Charset.forName("utf-8").decode(byteBuffer);

        for (int i = 0; i < charBuffer.limit(); i++) {
            System.out.print(charBuffer.get());
        }

        //输出:abcde     你好你好
    }
        //4:枚举常量:TRUNCATE_EXTING:以写入方式打开,清空文件,读取方式则忽略此选项
        //method_05();

    private static void method_05() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\test.txt");
        Path path = file.toPath();
        FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.WRITE);
        fileChannel.close();
    }
        //5:枚举常量:CREATE_NEW:创建一个新文件,如果文件已存在,则失败
        //method_06();

    private static void method_06() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\test3");
        Path path = file.toPath();
        FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.CREATE_NEW,
                StandardOpenOption.WRITE);
        fileChannel.close();
        //报错:Exception in thread "main" java.nio.file.FileAlreadyExistsException,已存在此文件
    }
        //6:枚举常量:DELETE_ON_CLOSE:关闭文件时删除
        //method_07();

    private static void method_07() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\aaa.txt");
        Path path = file.toPath();
        FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.DELETE_ON_CLOSE,
                StandardOpenOption.CREATE,StandardOpenOption.WRITE);
        //线程睡眠10秒,观察桌面,确实出现aaa.txt
        Thread.sleep(10_000);
        fileChannel.close();
    }
        //7:枚举常量:SPARSE:创建稀疏文件,
        //7.1:执行过后你会发现你的E盘多了一个162GB的txt文件,虽然里面只有一个字符'a',执行一次,删除就够了,不要多次执行,我就玩儿炸了,格式化了F盘
        //method_08();
    private static void method_08() throws Exception{
        File file = new File("F:\\a.txt");
        FileChannel fileChannel = FileChannel.open(file.toPath(),StandardOpenOption.CREATE,
                StandardOpenOption.WRITE);
        long fileSize = Integer.MAX_VALUE;
        fileSize = fileSize*3;
        fileSize = fileSize*3;
        fileSize = fileSize*3;
        fileSize = fileSize*3;
        fileChannel.position(fileSize);
        fileChannel.write(ByteBuffer.wrap("a".getBytes()));
        fileChannel.close();
    }
        //7.2:所以就要使用稀疏文件,对不存储数据的文件不占用空间,要用CREATE_NEW
        //mehtod_09();

    private static void mehtod_09() throws Exception{
        File file = new File("F:\\a.txt");
        FileChannel fileChannel = FileChannel.open(file.toPath(),StandardOpenOption.CREATE_NEW,
                StandardOpenOption.WRITE,StandardOpenOption.SPARSE);
        long fileSize = Integer.MAX_VALUE;
        fileSize = fileSize*3;
        fileSize = fileSize*3;
        fileSize = fileSize*3;
        fileSize = fileSize*3;
        fileChannel.position(fileSize);
        fileChannel.write(ByteBuffer.wrap("a".getBytes()));
        fileChannel.close();
    }
        //8:枚举常量:SYNC和DSYNC
        //8.1:SYNC:对文件或元数据的每次更新都同步写入底层设备
        //8.2:DSYNC:只更新文件内容每次同步到底层设备
        //method_10();

    private static void method_10() throws Exception{
        Thread thread1 = new Thread(){
            @Override
            public void run() {
                try {
                    File file = new File("C:\\Users\\10167\\Desktop\\test1.txt");
                    Path path = file.toPath();
                    FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.SYNC,StandardOpenOption.CREATE,StandardOpenOption.WRITE);
                    long startTime = System.currentTimeMillis();
                    for (int i = 0; i < 20000; i++) {
                        fileChannel.write(ByteBuffer.wrap("a".getBytes()));
                    }
                    long endTime = System.currentTimeMillis();
                    System.out.println("SYNC时间:"+(endTime  - startTime));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };

        Thread thread2 = new Thread(){
            @Override
            public void run() {
                try {
                    File file = new File("C:\\Users\\10167\\Desktop\\test2.txt");
                    Path path = file.toPath();
                    FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.DSYNC,StandardOpenOption.CREATE,StandardOpenOption.WRITE);
                    long startTime = System.currentTimeMillis();
                    for (int i = 0; i < 20000; i++) {
                        fileChannel.write(ByteBuffer.wrap("a".getBytes()));
                    }
                    long endTime = System.currentTimeMillis();
                    System.out.println("DSYNC时间:"+(endTime  - startTime));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };

        Thread thread3 = new Thread(){
            @Override
            public void run() {
                try {
                    File file = new File("C:\\Users\\10167\\Desktop\\test3.txt");
                    Path path = file.toPath();
                    FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.CREATE,StandardOpenOption.WRITE);
                    long startTime = System.currentTimeMillis();
                    for (int i = 0; i < 20000; i++) {
                        fileChannel.write(ByteBuffer.wrap("a".getBytes()));
                    }
                    long endTime = System.currentTimeMillis();
                    System.out.println("不同步写入设备的时间:"+(endTime  - startTime));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };


        thread1.start();
        thread2.start();
        thread3.start();


        /*输出:很明显,时间效率:不同步写入存储设备>DSYNC和SYNC,DSYNC和SYNC的时间要率要看是否写入元数据,没有的话,SYNC甚至可能要更快
        但是不同步写入设备的效率是SYNC的至少10倍以上
        不同步写入设备的时间:67
        SYNC时间:1349
        DSYNC时间:1350
        * */
    }
        //判断当前通道是否打开
        method_11();
    private static void method_11() throws Exception{
        File file = new File("C:\\Users\\10167\\Desktop\\test.txt");
        RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        System.out.println(fileChannel.isOpen());
        fileChannel.close();
        System.out.println(fileChannel.isOpen());
        /*输出:
        true
        false
        * */
    }
    }

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值