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?
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
Use a
BufferedInputStream
to read andBufferedOutputStream
to write. Take a look at this post: http://www.ajaxapp.com/2009/02/21/a-simple-java-ftp-connection-file-download-and-upload/Do not use any of the
Reader
orWriter
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 theInputStream
andOutputStream
classes; they do not interpret the data at all, while theReader
andWriter
classes interpret the data as characters. For exampleWhether 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.