Java中的URL连接(FTP) – 简单问题

我有一个简单的问题。 我正在尝试用Java将文件上传到我的ftp服务器。

我的计算机上有一个文件,我想制作该文件的副本并上传它。 我尝试手动将文件的每个字节写入输出流,但这对于复杂文件(如zip文件或pdf文件)不起作用。

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? 

只是为了踢,这是我试图做的:

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

例如,当我使用pdf执行此操作然后尝试打开我使用此程序运行的pdf时,它表示尝试打开pdf时发生错误。 我猜是因为我正在为文件写一个“\ n”? 如何在不执行此操作的情况下复制文件?

当您尝试复制二进制文件的逐字节精确内容时,请勿使用任何ReaderWriter类。 仅将这些用于纯文本! 而是使用InputStreamOutputStream类; 它们根本不解释数据,而ReaderWriter类将数据解释为字符。 例如

 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(如其他地方所建议的)将是一个很好的主意。 无论如何,这将是读取文件的方式。

使用BufferedInputStream读取和BufferedOutputStream进行写入。 看一下这篇文章: 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(); 

FTP通常会打开另一个数据传输连接。 所以我不相信URLConnection的这种方法会起作用。 我强烈建议您使用专门的ftp客户端。 Apache公共可能有一个。

看看这个http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html