URL Connection (FTP) in Java - Simple Question

后端 未结 3 1745
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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.

提交回复
热议问题