URL Connection (FTP) in Java - Simple Question

后端 未结 3 1747
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 02:17

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 t

相关标签:
3条回答
  • 2021-01-22 02:43

    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

    0 讨论(0)
  • 2021-01-22 02:46

    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();
    
    0 讨论(0)
  • 2021-01-22 02:47

    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.

    0 讨论(0)
提交回复
热议问题