問題描述
我有一個簡單的問題.我正在嘗試用 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?
推薦答案
嘗試復制字節時不要使用任何 Reader
或 Writer
類-for-byte 二進制文件的確切內容.僅將這些用于純文本!相反,使用 InputStream
和 OutputStream
類;它們根本不解釋數據,而 Reader
和 Writer
類將數據解釋為字符.例如
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.
這篇關于Java 中的 URL 連接 (FTP) - 簡單問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!