java 文件下载 linux windows

首先,将我的数据文件导出到项目部署服务器的文件夹里,然后将该文件通过项目接口下载下来。

针对这个问题,展开思考

一、在本地测试的时候

        1、使用文件流将文件从一个文件夹下载到另一个文件夹

        2、假如文件路径fileUrl为 d://outputFiles/test.xlsx   下载到pathUrl   d://temp/test.xlsx

代码如下

//文件所在位置
String fileUrl = "d://outputFiles/test.xlsx ";
//文件下载位置
String pathUrl = "d://temp/test.xlsx";

 try {        
            URL url = new URL(fileUrl);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(in);
            FileOutputStream out = new FileOutputStream(pathUrl );
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buffer = new byte[4096];
            int length = bis.read(buffer);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buffer);
            }
            bos.close();
            bis.close();
} catch (IOException e) {
    throw new RuntimeException(e);
}

        3、用这种方式会报一个错

java.lang.RuntimeException: java.net.MalformedURLException: unknown protocol: d
	at 

说明访问本地文件需要个协议,只需要在fileUrl前加一个

"file:///"

即可下载成功

二、将项目部署到linux服务器上

        1、文件应该是在服务器某个文件夹里,比如fileUrl = "/home/files/test.xlsx"

        2、通过接口将文件下载到本地pathUrl = "d://temp/test.xlsx"

        3、用以上代码,此时依旧使用 "file:///"协议,会发现我可以找到服务器上的文件,却找不到下载的路径,难道我下载的路径也是从服务器找的?

        报错信息:

java.io.FileNotFoundException: d:/temp/test.xlsx (No such file or directory)

        这里我还没找到解决方案

三、换一个方式下载服务器上的文件

        1、这里用连接ssh的方式获取服务器上的文件,并下载到本地

代码如下

import java.io.*;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class TestRemoteConnect {
//    https://blog.csdn.net/qq_41033385/article/details/109217665
    public static void main(String[] args) {
        String path = "/home/files/test.xlsx";//Linux服务器中的文件路径
        String hostName = "";//Linux服务器的地址
        int port = 22;//SSH访问22端口
        String username = "root";//Linux服务器的用户名
        String password = "";//Linux服务器的密码
        //创建SSH连接
        Connection connect = getConnect(hostName, username, password, port);
        //下载文件
        downloadFile(path,"d:/temp/", connect);
    }


    /**
     * 创建SSH连接
     * @param hostName
     * @param username
     * @param password
     * @param port
     * @return
     */
    public static Connection getConnect(String hostName, String username, String password, int port) {
        Connection conn = new Connection(hostName, port);
        try {
            // 连接到主机
            conn.connect();
            // 使用用户名和密码校验
            boolean isconn = conn.authenticateWithPassword(username, password);
            if (!isconn) {
                System.out.println("用户名称或者是密码不正确");
            } else {
                System.out.println("服务器连接成功.");
                return conn;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载文件
     * @param path
     * @param conn
     */
    public static void downloadFile(String path,String filePath, Connection conn) {
        if (conn != null) {
            Session session = null;
            try {
                FileOutputStream fileOut = null;
                session = conn.openSession();
                //设置读取文件大小 102400
                session.execCommand("tail -102400 ".concat(path));
                InputStream inputStream = new StreamGobbler(session.getStdout());
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                //写入到文件(注意文件保存路径的后面一定要加上文件的名称)
                fileOut = new FileOutputStream(filePath);
                BufferedOutputStream bos = new BufferedOutputStream(fileOut);
                byte[] buf = new byte[4096];
                int length = bis.read(buf);
                //保存文件
                while(length != -1)
                {
                    bos.write(buf, 0, length);
                    length = bis.read(buf);
                }
                bos.close();
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 连接的Session和Connection对象都需要关闭
                if (session != null) {
                    session.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }
        }
    }
}

直接下载成功

四、将流传到前端下载

        1、前端调用接口,配置{responseType: 'blob'}

        2、下载代码,fileUrl是绝对路径

   try {
            // fileUrl是指想要下载的文件的路径
            File file = new File(fileUrl);
            if (!file.exists()) {
                throw new RenException("文件不存在");
            }

            // 获取文件名
            String fileName = file.getName();
            fileName = URLEncoder.encode(fileName,"UTF-8");
            response.setHeader("Content-disposition","attachment;filename="+ fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            IOUtils.copy(fileInputStream,response.getOutputStream());
            response.flushBuffer();
            fileInputStream.close();
        } catch (IOException e) {
            throw new RenException(e.toString());
        }

参考博文:

java代码从Linux服务器的目录,下载目录中的文件到本地。(不是FTP,不是FTP,不是FTP)_java从linux服务器上下载文件-CSDN博客

 https://www.cnblogs.com/bpjj/p/11358499.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值