NIO基础-ByteBuffer,Channel

news2024/10/6 5:55:16

文章目录

    • 1. 三大组件
      • 1.1 Channel
      • 1.2 Buffer
      • 1.2 Selector
    • 2.ByteBuffer
      • 2.1 ByteBuffer 正确使用姿势
      • 2.2 ByteBuffer 结构
      • 2.3 ByteBuffer 常见方法
        • 分配空间
        • 向 buffer 写入数据
        • 从 buffer 读取数据
        • mark 和 reset
        • 字符串与 ByteBuffer 互转
        • 分散度集中写
        • byteBuffer黏包半包
    • 3. 文件编程
      • 3.1 FileChannel
        • 获取
        • 读取
        • 写入
        • 关闭
        • 位置
        • 大小
        • 强制写入
      • 3.2 两个 Channel 传输数据
      • 3.3 Path
      • 3.4 Files
        • 遍历目录
        • 删除多级目录
        • 拷贝多级目录

黑马视频地址:https://www.bilibili.com/video/BV1py4y1E7oA/?p=1

Netty是基于NIO(non-blocking io 非阻塞 IO),先了解nio

1. 三大组件

1.1 Channel

channel 是一个读写数据的双向通道,可以从 channel 将数据读入 buffer,也可以将 buffer 的数据写入 channel

在这里插入图片描述

常见的 Channel 有

  • FileChannel (文件)
  • DatagramChannel (UDP)
  • SocketChannel (TCP 客户端/服务端都能用)
  • ServerSocketChannel(TCP 服务端)

1.2 Buffer

buffer就是缓冲区,用来缓冲读写数据,常见的 buffer 有

  • ByteBuffer
    • MappedByteBuffer
    • DirectByteBuffer
    • HeapByteBuffer
  • ShortBuffer
  • IntBuffer
  • LongBuffer
  • FloatBuffer
  • DoubleBuffer
  • CharBuffer

1.2 Selector

字面理解就是选择器,作用就是配合一个线程来管理多个 channel,获取这些 channel 上发生的事件,这些 channel 工作在非阻塞模式下,不会让线程吊死在一个 channel 上。适合连接数特别多,但流量低的场景(low traffic)

在这里插入图片描述

调用 selector 的 select() 会阻塞直到 channel 发生了读写就绪事件,这些事件发生,select 方法就会返回这些事件交给 thread 来处理

2.ByteBuffer

简单案例:有一普通文本文件 data.txt,内容为

1234567890abcd

使用 FileChannel 来读取文件内容

@Slf4j
public class TestByteBuffer {

    public static void main(String[] args) throws FileNotFoundException {
        // 读取文件,并自动释放输入流
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            // 创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                //读出文件内容写入缓冲区
                int read = channel.read(buffer);
                log.info("读到的字节数:{}", read);
                if (read == -1) {
                    break;
                }
                //切换到读模式
                buffer.flip();
                while (buffer.hasRemaining()) {
                    log.info("实际字节:{}", (char) buffer.get());
                }
                //切换到写模式
                buffer.clear();
            }


        } catch (
                IOException e) {
            e.printStackTrace();
        }
    }
}

结果

11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 读到的字节数:10
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:1
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:2
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:3
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:4
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:5
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:6
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:7
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:8
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:9
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:0
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 读到的字节数:4
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:a
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:b
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:c
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 实际字节:d
11:15:40 [INFO ] [main] c.i.b.TestByteBuffer - 读到的字节数:-1

2.1 ByteBuffer 正确使用姿势

  1. 向 buffer 写入数据,例如调用 channel.read(buffer)
  2. 调用 flip() 切换至读模式
  3. 从 buffer 读取数据,例如调用 buffer.get()
  4. 调用 clear() 或 compact() 切换至写模式
  5. 重复 1~4 步骤

2.2 ByteBuffer 结构

ByteBuffer 有以下重要属性

  • capacity
  • position
  • limit

一开始

在这里插入图片描述

写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态
在这里插入图片描述
flip 动作发生后,position 切换为读取位置,limit 切换为读取限制

在这里插入图片描述
读取 4 个字节后,状态
在这里插入图片描述
clear 动作发生后,状态
在这里插入图片描述
compact 方法,是把未读完的部分向前压缩,然后切换至写模式
在这里插入图片描述
💡 调试工具类

public class ByteBufferUtil {
    private static final char[] BYTE2CHAR = new char[256];
    private static final char[] HEXDUMP_TABLE = new char[256 * 4];
    private static final String[] HEXPADDING = new String[16];
    private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
    private static final String[] BYTE2HEX = new String[256];
    private static final String[] BYTEPADDING = new String[16];

    static {
        final char[] DIGITS = "0123456789abcdef".toCharArray();
        for (int i = 0; i < 256; i++) {
            HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
            HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
        }

        int i;

        // Generate the lookup table for hex dump paddings
        for (i = 0; i < HEXPADDING.length; i++) {
            int padding = HEXPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding * 3);
            for (int j = 0; j < padding; j++) {
                buf.append("   ");
            }
            HEXPADDING[i] = buf.toString();
        }

        // Generate the lookup table for the start-offset header in each row (up to 64KiB).
        for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
            StringBuilder buf = new StringBuilder(12);
            buf.append(NEWLINE);
            buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
            buf.setCharAt(buf.length() - 9, '|');
            buf.append('|');
            HEXDUMP_ROWPREFIXES[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-hex-dump conversion
        for (i = 0; i < BYTE2HEX.length; i++) {
            BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
        }

        // Generate the lookup table for byte dump paddings
        for (i = 0; i < BYTEPADDING.length; i++) {
            int padding = BYTEPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding);
            for (int j = 0; j < padding; j++) {
                buf.append(' ');
            }
            BYTEPADDING[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-char conversion
        for (i = 0; i < BYTE2CHAR.length; i++) {
            if (i <= 0x1f || i >= 0x7f) {
                BYTE2CHAR[i] = '.';
            } else {
                BYTE2CHAR[i] = (char) i;
            }
        }
    }

    /**
     * 打印所有内容
     * @param buffer
     */
    public static void debugAll(ByteBuffer buffer) {
        int oldlimit = buffer.limit();
        buffer.limit(buffer.capacity());
        StringBuilder origin = new StringBuilder(256);
        appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
        System.out.println("+--------+-------------------- all ------------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
        System.out.println(origin);
        buffer.limit(oldlimit);
    }

    /**
     * 打印可读取内容
     * @param buffer
     */
    public static void debugRead(ByteBuffer buffer) {
        StringBuilder builder = new StringBuilder(256);
        appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
        System.out.println("+--------+-------------------- read -----------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
        System.out.println(builder);
    }

    private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
        if (isOutOfBounds(offset, length, buf.capacity())) {
            throw new IndexOutOfBoundsException(
                    "expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
                            + ") <= " + "buf.capacity(" + buf.capacity() + ')');
        }
        if (length == 0) {
            return;
        }
        dump.append(
                "         +-------------------------------------------------+" +
                        NEWLINE + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" +
                        NEWLINE + "+--------+-------------------------------------------------+----------------+");

        final int startIndex = offset;
        final int fullRows = length >>> 4;
        final int remainder = length & 0xF;

        // Dump the rows which have 16 bytes.
        for (int row = 0; row < fullRows; row++) {
            int rowStartIndex = (row << 4) + startIndex;

            // Per-row prefix.
            appendHexDumpRowPrefix(dump, row, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + 16;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(" |");

            // ASCII dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append('|');
        }

        // Dump the last row which has less than 16 bytes.
        if (remainder != 0) {
            int rowStartIndex = (fullRows << 4) + startIndex;
            appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + remainder;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(HEXPADDING[remainder]);
            dump.append(" |");

            // Ascii dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append(BYTEPADDING[remainder]);
            dump.append('|');
        }

        dump.append(NEWLINE +
                "+--------+-------------------------------------------------+----------------+");
    }

    private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
        if (row < HEXDUMP_ROWPREFIXES.length) {
            dump.append(HEXDUMP_ROWPREFIXES[row]);
        } else {
            dump.append(NEWLINE);
            dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
            dump.setCharAt(dump.length() - 9, '|');
            dump.append('|');
        }
    }

    public static short getUnsignedByte(ByteBuffer buffer, int index) {
        return (short) (buffer.get(index) & 0xFF);
    }
}

2.3 ByteBuffer 常见方法

分配空间

可以使用 allocate 方法为 ByteBuffer 分配空间,其它 buffer 类也有该方法

Bytebuffer buf = ByteBuffer.allocate(16);
Bytebuffer buf = ByteBuffer.allocateDirect(16)

//class java.nio.HeapByteBuffer java堆内存,读写效率较低,受到 GC 的影响
//class java.nio.DirectByteBuffer 直接内存,读写效率高(少一次拷贝),不会受 GC 影响,分配的效丰低
向 buffer 写入数据

有两种办法

  • 从Channel写到Buffer。

  • 通过Buffer的put()方法写到Buffer里。

int readBytes = channel.read(buf);
buf.put((byte)127);
从 buffer 读取数据

同样有两种办法

  • 从Buffer读取数据到Channel。
  • 使用get()方法从Buffer中读取数据。
int writeBytes = channel.write(buf);
byte b = buf.get();

get 方法会让 position 读指针向后走,如果想重复读取数据

  • 可以调用 rewind 方法将 position 重新置为 0
  • 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针
public static void main(String[] args) {
    //rewind
    ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.put(new byte[]{'a','b','c','d','e'});
    buffer.flip();
    buffer.get(new byte[4]);
    debugAll(buffer);
    buffer.rewind();
    debugAll(buffer);
    System.out.println((char)buffer.get());

    //get(i)
    debugAll(buffer);
    System.out.println((char)buffer.get(2));
    debugAll(buffer);
}
mark 和 reset

mark 是在读取时,做一个标记,记录position 位置,即使 position 改变,只要调用 reset 就能回到 mark 的位置

注意

rewind 和 flip 都会清除 mark 位置

public static void main(String[] args) {
    // mark & reset
    ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.put(new byte[]{'a','b','c','d','e'});
    buffer.flip();
    System.out.println((char)buffer.get());//a
    System.out.println((char)buffer.get());//b
    buffer.mark();//记录position位置
    System.out.println((char)buffer.get());//c
    System.out.println((char)buffer.get());//d
    buffer.reset();//重置到记录的position位置
    System.out.println((char)buffer.get());//c
    System.out.println((char)buffer.get());//d
}
字符串与 ByteBuffer 互转

字符串转buffer

  • buffer1.put(字符串.getBytes());
  • StandardCharsets.UTF_8.encode(字符串);
  • ByteBuffer.wrap(字符串.getBytes());

buffer转字符串

  • StandardCharsets.UTF_8.decode(buffer1).toString();
public static void main(String[] args) {
    //字符串转buffer
    ByteBuffer buffer1 = ByteBuffer.allocate(16);
    buffer1.put("nihao".getBytes());//写模式,转换要改为读模式
    debugAll(buffer1);

    ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("nihao");//读模式
    debugAll(buffer2);

    ByteBuffer buffer3 = ByteBuffer.wrap("nihao".getBytes());//读模式
    debugAll(buffer3);

    //buffer转字符串
    buffer1.flip();
    String s1 = StandardCharsets.UTF_8.decode(buffer1).toString();
    System.out.println(s1);

    String s2 = StandardCharsets.UTF_8.decode(buffer2).toString();
    System.out.println(s2);
}
分散度集中写

分散读取,有一个文本文件 parts.txt

onetwothree

使用如下方式读取,可以将数据填充至多个 buffer

public static void main(String[] args) throws IOException {
    try(FileChannel channel=new RandomAccessFile("part.txt","r").getChannel()) {
        ByteBuffer a = ByteBuffer.allocate(3);
        ByteBuffer b = ByteBuffer.allocate(3);
        ByteBuffer c = ByteBuffer.allocate(5);
        channel.read(new ByteBuffer[]{a,b,c});
        a.flip();
        b.flip();
        c.flip();
        debugAll(a);//one
        debugAll(b);//two
        debugAll(c);//three
    }
}

使用如下方式写入,可以将多个 buffer 的数据填充至 channel

public static void main(String[] args) throws IOException {
    ByteBuffer a = StandardCharsets.UTF_8.encode("hello");
    ByteBuffer b = StandardCharsets.UTF_8.encode("world");
    ByteBuffer c = StandardCharsets.UTF_8.encode("你好");
    try (FileChannel channel = new RandomAccessFile("new.txt", "rw").getChannel()) {
        channel.write(new ByteBuffer[]{a, b, c});
    }
}
byteBuffer黏包半包

网络上有多条数据发送给服务端,数据之间使用 \n 进行分隔,但由于某种原因这些数据在接收时,被进行了重新组合,例如原始数据有3条为

  • Hello,world\n
  • I’m zhangsan\n
  • How are you?\n
  • haha!\n

变成了下面的两个 byteBuffer (黏包,半包)

  • Hello,world\nI’m zhangsan\nHo
  • w are you?\nhaha!

现在要求你编写程序,将错乱的数据恢复成原始的按 \n 分隔的数据

public class TestByteBufferNianBao {

    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(source);

        source.put("w are you?\nhaha!\n".getBytes());
        split(source);
    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            //如果是 \n 证明是一句话
            if (source.get(i) == '\n') {
                //分配ByteBuffer大小
                int length = i + 1 - source.position();
                //用一个buffer存这一句话
                ByteBuffer buffer = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    buffer.put(source.get());
                }
                debugAll(buffer);
            }
        }
        //把半句话压入前面等待处理
        source.compact();
    }
}

3. 文件编程

3.1 FileChannel

获取

在使用FileChannel之前,必须先打开它。但是,我们无法直接打开一个FileChannel,需要通过使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例。

  • 通过 FileInputStream 获取的 channel 只能读
  • 通过 FileOutputStream 获取的 channel 只能写
  • 通过 RandomAccessFile 是否能读写根据构造 RandomAccessFile 时的读写模式决定
读取

该方法将数据从FileChannel读取到Buffer中。read()方法返回的int值表示了有多少字节被读到了Buffer中。如果返回-1,表示到了文件末尾。

int readBytes = channel.read(buffer);
写入

写入的正确姿势如下

ByteBuffer buffer = ...;
buffer.put(...); // 存入数据
buffer.flip();   // 切换读模式

while(buffer.hasRemaining()) {
    channel.write(buffer);
}

注意FileChannel.write()是在while循环中调用的。因为无法保证write()方法一次能向FileChannel写入多少字节,因此需要重复调用write()方法,直到Buffer中已经没有尚未写入通道的字节。

关闭

channel 必须关闭:channel.close(),不过调用了 FileInputStream、FileOutputStream 或者 RandomAccessFile 的 close 方法会间接地调用 channel 的 close 方法

位置

有时可能需要在FileChannel的某个特定位置进行数据的读/写操作。可以通过调用position()方法获取FileChannel的当前位置。

也可以通过调用position(long pos)方法设置FileChannel的当前位置

long pos = channel.positon();

大小

FileChannel实例的size()方法将返回该实例所关联文件的大小。

long size = channel.size();

强制写入

FileChannel.force()方法将通道里尚未写入磁盘的数据强制写到磁盘上。出于性能方面的考虑,操作系统会将数据缓存在内存中,所以无法保证写入到FileChannel里的数据一定会即时写到磁盘上。要保证这一点,需要调用force()方法。

force()方法有一个boolean类型的参数,指明是否同时将文件元数据(权限信息等)写到磁盘上。

channel.force(true);

3.2 两个 Channel 传输数据

public static void main(String[] args) {
    try (
            FileChannel from = new FileInputStream("from.txt").getChannel();
            FileChannel to = new FileOutputStream("to.txt").getChannel();
    ) {
        //效率高,底层会利用操作系统的零拷贝进行优化
        long size = from.size();
        // left 还剩多少未传
        for (long left = size; left > 0; ) {
            //每次实际传输的大小,2G是上限
            long transfer = from.transferTo(size - left, left, to);
            left -= transfer;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.3 Path

jdk7 引入了 Path 和 Paths 类

  • Path 用来表示文件路径
  • Paths 是工具类,用来获取 Path 实例
Path source = Paths.get("1.txt"); // 相对路径 使用 user.dir 环境变量来定位 1.txt

Path source = Paths.get("d:\\1.txt"); // 绝对路径 代表了  d:\1.txt

Path source = Paths.get("d:/1.txt"); // 绝对路径 同样代表了  d:\1.txt

Path projects = Paths.get("d:\\data", "projects"); // 代表了  d:\data\projects
  • . 代表了当前路径
  • .. 代表了上一级路径

例如目录结构如下

d:
	|- data
		|- projects
			|- a
			|- b

代码

Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
System.out.println(path);
System.out.println(path.normalize()); // 正常化路径

会输出

d:\data\projects\a\..\b
d:\data\projects\b

3.4 Files

检查文件是否存在

Path path = Paths.get("helloword/data.txt");
System.out.println(Files.exists(path));

创建一级目录

Path path = Paths.get("helloword/d1");
Files.createDirectory(path);
  • 如果目录已存在,会抛异常 FileAlreadyExistsException
  • 不能一次创建多级目录,否则会抛异常 NoSuchFileException

创建多级目录用

Path path = Paths.get("helloword/d1/d2");
Files.createDirectories(path);

拷贝文件

Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/target.txt");

Files.copy(source, target);
  • 如果文件已存在,会抛异常 FileAlreadyExistsException

如果希望用 source 覆盖掉 target,需要用 StandardCopyOption 来控制

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

移动文件

Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/data.txt");

Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
  • StandardCopyOption.ATOMIC_MOVE 保证文件移动的原子性

删除文件

Path target = Paths.get("helloword/target.txt");

Files.delete(target);
  • 如果文件不存在,会抛异常 NoSuchFileException

删除目录

Path target = Paths.get("helloword/d1");

Files.delete(target);
  • 如果目录还有内容,会抛异常 DirectoryNotEmptyException
遍历目录
public static void main(String[] args) throws IOException {
    Path path = Paths.get("D:\\Program Files (x86)\\DingDing");
    AtomicInteger dirCount = new AtomicInteger();
    AtomicInteger fileCount = new AtomicInteger();
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            System.out.println("+" + dir);
            dirCount.incrementAndGet();
            return super.preVisitDirectory(dir, attrs);
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("-" + file);
            fileCount.incrementAndGet();
            return super.visitFile(file, attrs);
        }
    });
    System.out.println("dirCount:" + dirCount);
    System.out.println("fileCount:" + fileCount);

}
删除多级目录
public static void main(String[] args) throws IOException {
    Path path = Paths.get("D:\\Program Files (x86)\\DingDing - 副本");
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            //访问文件的时候删除文件
            Files.delete(file);
            return super.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            //退出文件夹的时候删除文件夹
            Files.delete(dir);
            return super.postVisitDirectory(dir, exc);
        }
    });
}
拷贝多级目录
public static void main(String[] args) throws IOException {
    String source = "D:\\Program Files (x86)\\DingDing";
    String target = "D:\\Program Files (x86)\\DingDingfuben";

    Files.walk(Paths.get(source)).forEach(path -> {
        try {
            String targetName = path.toString().replace(source, target);
            //如果是目录
            if (Files.isDirectory(path)) {
                Files.createDirectory(Paths.get(targetName));
            }
            //如果是文件
            else if (Files.isRegularFile(path)) {
                Files.copy(path, Paths.get(targetName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1083769.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

简历石层大海,为何今年秋招那么难?技术面考官想听啥?

上个月发完关于《2023年的IC求职究竟有多难&#xff1f;》文章&#xff0c;后台就出现很多私信&#xff0c;大家都在频繁的问秋招的事情&#xff0c;今年的秋招提前批让很多人直接破防&#xff0c;感觉书读了那么久&#xff0c;学校也还不错&#xff0c;但是为什么企业招聘的简…

单车模型:横向动力学

文章目录 1 模型推导2 参考资料 较高车速下&#xff0c;不能再假设车轮朝向和车轮速度一致。因此运动学模型在这里的误差就会比较大&#xff0c;必须要考虑动力学模型。 现考虑2自由度单车模型&#xff0c;如下图所示。2自由度表示为&#xff1a; 车辆横线位置 y y y&#xff…

2023-2024-1 高级语言程序设计实验一: 选择结构

7-1 古时年龄称谓知多少&#xff1f; 输入一个人的年龄&#xff08;岁&#xff09;&#xff0c;判断出他属于哪个年龄段 &#xff1f; 0-9 &#xff1a;垂髫之年&#xff1b; 10-19&#xff1a; 志学之年&#xff1b; 20-29 &#xff1a;弱冠之年&#xff1b; 30-39 &#…

Docker开启远程访问+idea配置docker+dockerfile发布java项目

一、docker开启远程访问 1.编辑docker服务文件 vim /usr/lib/systemd/system/docker.servicedocker.service原文件如下&#xff1a; [Unit] DescriptionDocker Application Container Engine Documentationhttps://docs.docker.com Afternetwork-online.target docker.socke…

【深蓝学院】手写VIO第7章--VINS初始化和VIO系统--笔记

0. 内容 1. VIO回顾 整个视觉前端pipeline回顾&#xff1a; 两帧图像&#xff0c;可提取特征点&#xff0c;特征匹配&#xff08;描述子暴力匹配或者光流&#xff09;已知特征点匹配关系&#xff0c;利用几何约束计算relative pose([R|t])&#xff0c;translation只有方向&…

2023年中国睡眠检测仪产量、销量及市场规模分析[图]

睡眠检测仪行业是指生产和销售用于监测和评估人类睡眠质量和睡眠相关指标的设备和工具的行业。睡眠检测仪可以通过监测人体的脑电图、心率、呼吸、体动等生理信号&#xff0c;来评估睡眠的深度、时长、睡眠阶段的分布等信息&#xff0c;帮助人们了解自己的睡眠状况&#xff0c;…

一款轻量级事件驱动型应用程序框架

QP™/C 实时嵌入式框架 &#xff08;RTEF&#xff09; 是专为实时嵌入式 &#xff08;RTE&#xff09; 系统量身定制的活动对象计算模型的轻量级实现。QP 既是用于构建由活动对象&#xff08;参与者&#xff09;组成的应用程序的软件基础结构&#xff0c;也是用于以确定性方式执…

有更新:2023华为HCIA+HCIP最全Datacom题库解析(附全套文档赠送)

2023华为数通Datacom认证考试题库更新&#xff0c;答案解析&#xff1a; 1、所示的BGP/MPLS IP VPN场景&#xff0c;CE和PE之间运行0SPF协议&#xff0c;且区域号为0&#xff0c;当PE1和PE2的域标识符都为NULL时&#xff0c;PE2将向CE2发 送以下哪一类型的LSA? A.Type2 B.T…

了解三层架构:表示层、业务逻辑层、数据访问层

目录 背景&#xff1a; 三层架构 什么是三层: 分层的目的&#xff1a; 三层的结构关系​编辑 三层表现形式:​编辑 三层的优缺点&#xff1a; 总结: 背景&#xff1a; 三层架构是一种软件设计模式&#xff0c;可称为客户端-服务器-架构&#xff0c;把各个功能模块划分…

第二证券:汇金增持有望催化银行板块 白酒企稳信号凸显

昨日&#xff0c;两市股指盘中震动上扬&#xff0c;创业板指、科创50指数一度涨超1%&#xff0c;但沪指午后涨幅逐渐回落。到收盘&#xff0c;沪指涨0.12%报3078.96点&#xff0c;深成指涨0.35%报10084.89点&#xff0c;创业板指涨0.8%报2003.9点&#xff0c;科创50指数涨1.29%…

3.3 数据定义

思维导图&#xff1a; 前言&#xff1a; **核心概念**&#xff1a; - 关系数据库支持**三级模式结构**&#xff1a;模式、外模式、内模式。 - 这些模式中包括了如&#xff1a;模式、表、视图和索引等基本对象。 - SQL的数据定义功能主要包括了模式定义、表定义、视图和索引的定…

AnolisOS升级SSH,不升级SSL

由于ssh有漏洞需要升级&#xff0c;但是为了最小化升级不影响ssl&#xff0c;因为ssl里面带了加密库&#xff0c;系统中很多核心服务的加密都是用ssl进行加密的&#xff08;像网络服务&#xff0c;系统用户登录等&#xff09;&#xff0c;如果ssl升级出现不兼容&#xff0c;就可…

【Python语义分割】Segment Anything(SAM)模型全局语义分割代码+掩膜保存(二)

我上篇博文分享了Segment Anything&#xff08;SAM&#xff09;模型的基本操作&#xff0c;这篇给大家分享下官方的整张图片的语义分割代码&#xff08;全局&#xff09;&#xff0c;同时我还修改了一部分支持掩膜和叠加影像的保存。 1 Segment Anything介绍 1.1 概况 Meta A…

201、RabbitMQ 之 Exchange 典型应用模型 之 工作队列(Work Queue)

目录 ★ 工作队列介绍代码演示测试注意点1&#xff1a;注意点2&#xff1a; ★ 工作队列介绍 工作队列&#xff1a; 就是让多个消费者竞争消费同一个消息队列的消息&#xff0c;相当于多个消费者共享消息队列。 ▲ RabbitMQ可以让多个消费者竞争消费同一个消息队列 ▲ 消息队…

MS4344:24bit、192kHz 双通道数模转换电路

MS4344 是一款立体声数模转换芯片&#xff0c;内含插值滤波器、 multi-bit 数模转换器、输出模拟滤波器。 MS4344 支持大部分 的音频数据格式。 MS4344 基于一个带线性模拟低通滤波器的 四阶 multi-bit Δ-Σ 调制器&#xff0c;而且本芯片可以通过检测信号频率 和主时钟频…

【Axure高保真原型】冻结固定中继器表格首行+首尾列

今天和大家分享冻结固定中继器表格首行首尾列的原型模板&#xff0c;我们可以滚动或者拖动滚动条上下左右查看表格更多的数据&#xff0c;表格的首行和首尾两列都是固定的&#xff0c;鼠标移入对应行会有高亮显示的效果&#xff0c;点击操作列的删除按钮可以删除该行数据。那这…

智能油烟机 优化烹饪体验

如果说空调是夏天最伟大的发明&#xff0c;那么油烟机则是健康厨房的伟大推进者。随着科技的发展&#xff0c;智能化的油烟机逐渐走进了人们的日常生活。每当我们在爆炒、油炸食物的时候&#xff0c;油烟总能呛得人眼睛痛、鼻子难受&#xff0c;传统的油烟机面前我们还需要手动…

蒙自源荣登“2022年度中国快餐TOP100”榜单!

2023年9月26日&#xff0c;由中国烹饪协会主办的第27届中国快餐产业大会在浙江宁波盛大召开。 对于行业而言&#xff0c;这是一次至关重要的聚会。本次大会以“增量博弈&#xff0c;智造无限机遇”为主题&#xff0c;聚集了众多餐饮业的意见领袖&#xff0c;共同探讨行业发展焦…

第二证券:市净率高好还是低好?

市净率是一个衡量公司股票投资价值的指标&#xff0c;通过比较公司股票价格和公司每股净资产的比值来评估公司股票的估值水平。市净率高好还是低好这个问题并没有一个简单的答案&#xff0c;取决于具体的市场环境和投资者的需求。本文将从多个角度分析市净率高好还是低好。 首…

云HIS医院信息化管理平台源码,SaaS模式、springboot框架

HIS系统作为医院信息化的核心业务系统&#xff0c;如今已成为各个医疗机构的必备品了。大到三级二级医院&#xff0c;小到社区卫生服务中心&#xff0c;门诊&#xff08;门诊管理系统也可以理解为门诊的his系统&#xff0c;只是功能简单&#xff0c;模块较少&#xff09;。随着…