URL Connection (FTP) in Java - Simple Question

2019-02-25 19:45发布

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

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("\n".getBytes());
    line = br.readLine();
}
os.close();

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 "\n" to the file? How do I copy the file without doing this?

标签: java url ftp
3条回答
成全新的幸福
2楼-- · 2019-02-25 20:06

FTP usually opens another connection for data transfer. So I am not convinced that this approach with URLConnection is going to work. I highly recommend that you use specialized ftp client. Apache commons may have one.

Check this out http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html

查看更多
聊天终结者
3楼-- · 2019-02-25 20:11

Use a BufferedInputStream to read and BufferedOutputStream to write. Take a look at this post: 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();
查看更多
Explosion°爆炸
4楼-- · 2019-02-25 20:26

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);
}

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.

查看更多
登录 后发表回答