Java 中的 URL 连接 (FTP) - 简单问题

2022-01-09 00:00:00 url ftp java

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

I have a simple question. I'm trying to upload a file to my ftp server in Java.

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

I have a file on my computer, and I want to make a copy of that file and upload it. I tried manually writing each byte of the file to the output stream, but that doesn't work for complicated files, like zip files or pdf files.

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?

只是为了好玩,这是我尝试做的:

Just for kicks, here is what I tried to 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("
".getBytes());
    line = br.readLine();
}
os.close();

例如,当我使用 pdf 执行此操作,然后尝试打开使用此程序运行的 pdf 时,它说尝试打开 pdf 时发生错误.我猜是因为我正在向文件写入 "?如果不这样做,如何复制文件?

For example, when I do this with a pdf and then try and open the pdf that I run with this program, it says an error occurred when trying to open the pdf. I'm guessing because I am writing a " " to the file? How do I copy the file without doing this?

推荐答案

尝试复制字节时不要使用任何 ReaderWriter 类-for-byte 二进制文件的确切内容.仅将这些用于纯文本!相反,使用 InputStreamOutputStream 类;它们根本不解释数据,而 ReaderWriter 类将数据解释为字符.例如

Do not use any of the Reader or Writer classes when you're trying to copy the byte-for-byte exact contents of a binary file. Use these only for plain text! Instead, use the InputStream and OutputStream classes; they do not interpret the data at all, while the Reader and Writer classes interpret the data as characters. For example

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(如其他地方所建议的)将是一个好主意.无论如何,这将是读取文件的方式.

Whether your URLConnection usage is correct here, I don't know; using Apache Commons FTP (as suggested elsewhere) would be an excellent idea. Regardless, this would be the way to read the file.

相关文章