java链接ftp_Java中的URL连接(FTP)-简单问题

"博主在尝试使用Java通过FTP上传文件到服务器时遇到问题。当直接读取文件内容并写入输出流时,对于复杂的文件类型(如zip或pdf),会导致文件损坏。问题可能出在使用换行符" "来分隔文件内容。寻求解决方案如何正确地将整个文件内容无损地上传到FTP服务器。"
摘要由CSDN通过智能技术生成

我有一个简单的问题。我正在尝试将文件上传到Java中的ftp服务器。

我的计算机上有一个文件,我想复制该文件并上传。我尝试将文件的每个字节手动写入输出流,但这不适用于复杂文件,例如zip文件或pdf文件。

File file = some file on my computer;

String name = file.getName();

URL url = new URL("ftp://user:password@domain.com/" + name +";type=i");

URLConnection urlc = url.openConnection();

OutputStream os = urlc.getOutputStream();

//then what do I do?

只是为了踢球,这是我尝试做的事情:

OutputStream os = urlc.getOutputStream();

BufferedReader br = new BufferedReader(new FileReader(file));

String line = br.readLine();

while(line != null && (!line.equals(""))) {

os.write(line.getBytes());

os.write("\n".getBytes());

line = br.readLine();

}

os.close();

例如,当我使用pdf进行此操作,然后尝试打开使用该程序运行的pdf时,它表示尝试打开pdf时发生错误。我猜是因为我要在文件中写入“ \

n”?如何不执行此操作就复制文件?

package com.kwantler.YN_EW.service.impl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class FilePhoto { /** * 从网络Url下载文件 * * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置超时间为3秒 conn.setConnectTimeout(5 * 1000); // 防止屏蔽程序抓而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 得到输入流 InputStream inputStream = conn.getInputStream(); // 获自己数组 byte[] getData = readInputStream(inputStream); // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } System.out.println("info:" + url + " download success"); } /** * 从输入流字节数组 * * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } public static void main(String[] args) { try { downLoadByUrl( "https://www.mybiosource.com/images/tds/protocol_samples/MBS700_Antibody_Set_Sandwich_ELISA_Protocol.pdf", "ELISA.pdf", "E:/upload/protocol"); } catch (Exception e) { // TODO: handle exception } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值