【问题标题】:URL Connection (FTP) in Java - Simple QuestionJava 中的 URL 连接 (FTP) - 简单问题
【发布时间】:2011-08-20 23:49:02
【问题描述】:

我有一个简单的问题。我正在尝试用 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”?如果不这样做,如何复制文件?

【问题讨论】:

  • 不起作用是什么意思?
  • 好吧,我尝试打开我试图以这种方式复制的 pdf,它说文件出现错误。

标签: java url ftp


【解决方案1】:

当您尝试逐字节复制二进制文件的精确内容时,请勿使用任何ReaderWriter 类。仅将这些用于纯文本!相反,使用InputStreamOutputStream 类;他们根本不解释数据,而ReaderWriter 类将数据解释为字符。例如

OutputStream os = urlc.getOutputStream();
FileInputStreamReader fis = new FileInputStream(file);
byte[] buffer = new byte[1000];
int count = 0;
while((count = fis.read(buffer)) > 0) {
    os.write(buffer, 0, count);
}

你的URLConnection在这里使用是否正确,我不知道;使用 Apache Commons FTP(如其他地方所建议的)将是一个好主意。无论如何,这将是读取文件的方式。

【讨论】:

  • 嗯,你需要both 东西——你必须用Input/OutputStreams 读写文件,你需要使用FTPClient 之类的东西来正确传输它。
  • FTP 客户端可以以文本或二进制形式传输数据。 PDF 需要二进制文件。
【解决方案2】:

使用BufferedInputStream 读取和BufferedOutputStream 写入。看看这个帖子:http://www.ajaxapp.com/2009/02/21/a-simple-java-ftp-connection-file-download-and-upload/

InputStream is = new FileInputStream(localfilename);
BufferedInputStream bis = new BufferedInputStream(is);
OutputStream os =m_client.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int readCount;
while( (readCount = bis.read(buffer)) > 0) {
    bos.write(buffer, 0, readCount);
}
bos.close();

【讨论】:

    【解决方案3】:

    FTP 通常会打开另一个连接进行数据传输。 所以我不相信这种使用 URLConnection 的方法会成功 去工作。 我强烈建议您使用专门的 ftp 客户端。阿帕奇公地 可能有一个。

    看看这个 http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html

    【讨论】:

    • 我现在正在使用 FTPClient。而且pdf仍然一团糟。
    • 实际上(至少使用 Sun JRE)URLConnection 使用 sun.net.ftp.FTPClient 处理 ftp:// ,即使它没有记录,我仍然更喜欢它而不是 commons.net.ftp.FTPClient (主要是由于代理实现)。就像一个与问题中的实际问题完全无关的旁注:)
    猜你喜欢
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多