码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • Java中PDF文件传输有哪些方法?


    专栏集锦,大佬们可以收藏以备不时之需:

    Spring Cloud 专栏:http://t.csdnimg.cn/WDmJ9

    Python 专栏:http://t.csdnimg.cn/hMwPR

    Redis 专栏:http://t.csdnimg.cn/Qq0Xc

    TensorFlow 专栏:http://t.csdnimg.cn/SOien

    Logback 专栏:http://t.csdnimg.cn/UejSC

    量子计算:

    量子计算 | 解密著名量子算法Shor算法和Grover算法

    AI机器学习实战:

    AI机器学习实战 | 使用 Python 和 scikit-learn 库进行情感分析

    AI机器学习 | 基于librosa库和使用scikit-learn库中的分类器进行语音识别

    Python实战:

    Python实战 | 使用 Python 和 TensorFlow 构建卷积神经网络(CNN)进行人脸识别

    Spring Cloud实战:

    Spring Cloud实战 |分布式系统的流量控制、熔断降级组件Sentinel如何使用

    Spring Cloud 实战 | 解密Feign底层原理,包含实战源码

    Spring Cloud 实战 | 解密负载均衡Ribbon底层原理,包含实战源码

    1024程序员节特辑文章:

    1024程序员狂欢节特辑 | ELK+ 协同过滤算法构建个性化推荐引擎,智能实现“千人千面”

    1024程序员节特辑 | 解密Spring Cloud Hystrix熔断提高系统的可用性和容错能力

    1024程序员节特辑 | ELK+ 用户画像构建个性化推荐引擎,智能实现“千人千面”

    1024程序员节特辑 | OKR VS KPI谁更合适?

    1024程序员节特辑 | Spring Boot实战 之 MongoDB分片或复制集操作

    Spring实战系列文章:

    Spring实战 | Spring AOP核心秘笈之葵花宝典

    Spring实战 | Spring IOC不能说的秘密?

    国庆中秋特辑系列文章:

    国庆中秋特辑(八)Spring Boot项目如何使用JPA

    国庆中秋特辑(七)Java软件工程师常见20道编程面试题

    国庆中秋特辑(六)大学生常见30道宝藏编程面试题

    国庆中秋特辑(五)MySQL如何性能调优?下篇

    国庆中秋特辑(四)MySQL如何性能调优?上篇

    国庆中秋特辑(三)使用生成对抗网络(GAN)生成具有节日氛围的画作,深度学习框架 TensorFlow 和 Keras 来实现

    国庆中秋特辑(二)浪漫祝福方式 使用生成对抗网络(GAN)生成具有节日氛围的画作

    国庆中秋特辑(一)浪漫祝福方式 用循环神经网络(RNN)或长短时记忆网络(LSTM)生成祝福诗词

    目录

    • 1. 使用Java内置的I/O类
          • 示例代码
    • 2. 使用Apache Commons IO
          • 示例代码
    • 3. 使用Netty进行网络传输
          • 示例代码
    • 4. 使用Socket编程
          • 示例代码
    • 5. 使用iText库生成PDF并传输
          • 示例代码

    在Java中,PDF文件的传输可以通过多种方式实现,包括使用Java内置的I/O类、第三方库如Apache Commons IO、Netty等,以及通过网络协议进行传输。以下是一些常见的PDF文件传输方法,以及相应的代码示例。

    在这里插入图片描述

    1. 使用Java内置的I/O类

    Java的InputStream和OutputStream类可以用来读取和写入PDF文件。这种方法不涉及任何第三方库,但可能需要手动处理文件的读写。

    示例代码
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class PDFTransferExample {
        public static void main(String[] args) {
            // 读取PDF文件
            try (FileInputStream fis = new FileInputStream("source.pdf")) {
                // 写入PDF文件
                try (FileOutputStream fos = new FileOutputStream("destination.pdf")) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    2. 使用Apache Commons IO

    Apache Commons IO提供了更高级的I/O操作,如FileUtils类可以用来简化文件的读写过程。

    示例代码
    import org.apache.commons.io.FileUtils;
    
    import java.io.File;
    import java.io.IOException;
    
    public class PDFTransferApacheCommonsIO {
        public static void main(String[] args) {
            File sourceFile = new File("source.pdf");
            File destinationFile = new File("destination.pdf");
    
            try {
                FileUtils.copyFile(sourceFile, destinationFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3. 使用Netty进行网络传输

    Netty是一个高性能的网络编程框架,可以用来通过网络传输PDF文件。

    示例代码
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.HttpObjectAggregator;
    import io.netty.handler.codec.http.HttpRequestDecoder;
    import io.netty.handler.codec.http.HttpResponseEncoder;
    import io.netty.handler.codec.http.LastHttpContent;
    import io.netty.handler.stream.ChunkedStream;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    
    public class NettyPDFServer {
        public static void main(String[] args) {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup)
                 .channel(NioServerSocketChannel.class)
                 .childHandler(new ChannelInitializer<SocketChannel>() {
                     @Override
                     public void initChannel(SocketChannel ch) throws Exception {
                         ch.pipeline().addLast(new HttpRequestDecoder(), new HttpResponseEncoder(),
                             new HttpObjectAggregator(1024 * 1024 * 10), new NettyPDFServerHandler());
                     }
                 })
                 .option(ChannelOption.SO_BACKLOG, 128)
                 .childOption(ChannelOption.SO_KEEPALIVE, true);
    
                b.bind(8080).sync().channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }
    }
    
    class NettyPDFServerHandler extends SimpleChannelInboundHandler<HttpRequest> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
            if (req.getMethod().equals(HttpMethod.GET)) {
                File file = new File("source.pdf");
                FileInputStream fis = new FileInputStream(file);
                ctx.write(new LastHttpContent(
                    ctx.newChunkedFile(FileUtils.readFileToByteArray(file)),
                    HttpResponseStatus.OK,
                    req.headers(),
                    "application/pdf"
                ));
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    4. 使用Socket编程

    Java的Socket API可以用来在局域网或互联网上进行文件传输。

    示例代码
    import java.io.*;
    import java.net.Socket;
    
    public class PDFSocketServer {
        public static void main(String[] args) {
            int port = 8080;
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                System.out.println("Server is listening on port " + port);
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected: " + clientSocket.getInetAddress());
    
                try (BufferedInputStream in = new BufferedInputStream(
                         new FileInputStream("source.pdf"));
                     BufferedOutputStream out = new BufferedOutputStream(
                         clientSocket.getOutputStream())) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    5. 使用iText库生成PDF并传输

    iText是一个强大的PDF处理库,可以用来生成PDF文件,并通过网络传输。

    示例代码
    import com.itextpdf.text.Document;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.text.pdf.PdfReader;
    import com.itextpdf.text.pdf.PdfCopy;
    import com.itextpdf.text.pdf.PdfContentByte;
    
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    
    public class PDFiTextExample {
        public static void main(String[] args) {
            Document document = new Document();
            try (PdfWriter.getInstance(document, new FileOutputStream("example.pdf"))) {
                document.open();
                document.add(new Paragraph("Hello, iText!"));
                document.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            Socket socket = new Socket("localhost", 8080);
            try (InputStream in = new FileInputStream("example.pdf");
                 OutputStream out = socket.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
  • 相关阅读:
    y124.第七章 服务网格与治理-Istio从入门到精通 -- Sidecar及流量拦截机制(十)
    【记事本 】dom操作的类型
    Mysql事物详解(重要)
    14. UART串口通信
    论文解读(KP-GNN)《How Powerful are K-hop Message Passing Graph Neural Networks》
    软考——软件工程基础知识
    Hadoop的伪分布式安装
    C++迭代器失效
    串口调速小车1
    记录一下 Chrome浏览器打印时崩溃问题
  • 原文地址:https://blog.csdn.net/superdangbo/article/details/136284640
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号