ByteBuffer和Files和Paths

String 与 ByteBuffer的互转

 // 1 将字符串转为ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(20);
        buffer.put("hello".getBytes());
        System.out.println(buffer);
        // 2 Charset
        ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("hello");
        System.out.println(buffer1);
        // 3 wrap
        ByteBuffer buffer2 = ByteBuffer.wrap("hello".getBytes());
        System.out.println(buffer2);

        // 将ByteBuffer转为String
        String mes = StandardCharsets.UTF_8.decode(buffer2).toString();
        System.out.println(mes);

Paths 与 Files 的使用

创建一级目录

try {
    Path path = Paths.get("hello");
     Files.createDirectory(path);
 } catch (IOException e) {
     e.printStackTrace();
 }

如果目录已存在,会跑出异常 FileAireadyExistsException
不能创建多级目录,否在会抛出NosuchFileException

创建多级目录

try {
  	Path path = Paths.get("hello/3/3/2");
    Files.createDirectories(path);
} catch (IOException e) {
    e.printStackTrace();
  }

文件拷贝

try {
            Path path = Paths.get("hello/1.txt");
            Path target = Paths.get("hello/2.txt");
            Files.copy(path,target);
        } catch (IOException e) {
            e.printStackTrace();
        }

如果文件已经存在,则会抛异常FileAlreadyExistsException
如果希望覆盖,可以用重载的方法

try {
   Path path = Paths.get("hello/1.txt");
     Path target = Paths.get("hello/2.txt");
     Files.copy(path,target, StandardCopyOption.REPLACE_EXISTING);
 } catch (IOException e) {
     e.printStackTrace();
 }

遍历文件

 AtomicInteger dirCount = new AtomicInteger();
        AtomicInteger fileCount = new AtomicInteger();
        try {
            Files.walkFileTree( Paths.get("/Users/mac/IdeaProjects/spring-demos"),new SimpleFileVisitor<Path>(){
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    dirCount.getAndIncrement();
                    return super.preVisitDirectory(dir, attrs);
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.toString().endsWith(".java")) {
                        fileCount.getAndIncrement();
                        System.out.println(file);
                    }
                    return super.visitFile(file, attrs);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("目录:" + dirCount + " java:" + fileCount);

删除非空文件夹

try {
            Files.walkFileTree(Paths.get("/Users/mac/IdeaProjects/spring-demos/hello"),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);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

文件复制

 String source ="/Users/mac/Desktop/111";
        String target ="/Users/mac/Desktop/222";

        try {
            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 (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
先写客户端: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileClient { public static void main(String[] args) throws IOException { // 1. 创建 SocketChannel,并连接到服务端地址 SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 8888)); System.out.println("连接服务器成功"); // 2. 读取文件并发送给服务端 Path filePath = Paths.get("D:/1.jpg"); byte[] fileBytes = Files.readAllBytes(filePath); ByteBuffer buffer = ByteBuffer.wrap(fileBytes); while (buffer.hasRemaining()) { socketChannel.write(buffer); } System.out.println("文件发送成功"); // 3. 关闭 SocketChannel socketChannel.close(); } } ``` 然后是服务端: ```java import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; public class FileServer { public static void main(String[] args) throws IOException { // 1. 创建 ServerSocketChannel,并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress(8888)); System.out.println("服务器启动,等待客户端连接"); // 2. 接受客户端连接,并接收文件 SocketChannel socketChannel = serverSocketChannel.accept(); System.out.println("客户端已连接"); ByteBuffer buffer = ByteBuffer.allocate(1024); Path filePath = Paths.get("D:/2.jpg"); FileOutputStream fileOutputStream = new FileOutputStream(filePath.toFile()); int len; while ((len = socketChannel.read(buffer)) > 0) { buffer.flip(); fileOutputStream.getChannel().write(buffer); buffer.clear(); } System.out.println("文件接收成功"); // 3. 关闭 SocketChannel 和 ServerSocketChannel socketChannel.close(); serverSocketChannel.close(); // 4. 返回字符串“文件已接收” System.out.println("文件已接收"); } } ``` 注释如下: 1. 客户端: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileClient { public static void main(String[] args) throws IOException { // 1. 创建 SocketChannel,并连接到服务端地址 SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 8888)); System.out.println("连接服务器成功"); // 2. 读取文件并发送给服务端 Path filePath = Paths.get("D:/1.jpg"); // 文件路径 byte[] fileBytes = Files.readAllBytes(filePath); // 读取文件 ByteBuffer buffer = ByteBuffer.wrap(fileBytes); // 包装成 ByteBuffer while (buffer.hasRemaining()) { // 发送文件 socketChannel.write(buffer); } System.out.println("文件发送成功"); // 3. 关闭 SocketChannel socketChannel.close(); } } ``` 2. 服务端: ```java import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; public class FileServer { public static void main(String[] args) throws IOException { // 1. 创建 ServerSocketChannel,并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress(8888)); System.out.println("服务器启动,等待客户端连接"); // 2. 接受客户端连接,并接收文件 SocketChannel socketChannel = serverSocketChannel.accept(); System.out.println("客户端已连接"); ByteBuffer buffer = ByteBuffer.allocate(1024); // 读取数据的缓冲区 Path filePath = Paths.get("D:/2.jpg"); // 文件路径 FileOutputStream fileOutputStream = new FileOutputStream(filePath.toFile()); // 创建文件输出流 int len; while ((len = socketChannel.read(buffer)) > 0) { // 读取数据并写入文件 buffer.flip(); fileOutputStream.getChannel().write(buffer); buffer.clear(); } System.out.println("文件接收成功"); // 3. 关闭 SocketChannel 和 ServerSocketChannel socketChannel.close(); serverSocketChannel.close(); // 4. 返回字符串“文件已接收” System.out.println("文件已接收"); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值