匿名用户URL的写法
URL url = new URL("ftp://@192.168.30.190/xxx.pdf");
匿名用户使用sun.net.ftp.FtpClient连接的写法
FtpClient ftpClient = new FtpClient();
ftpClient.openServer("192.168.30.190", 21);
ftpClient.login("anonymous", "");
需要注意的是,由于是匿名用户,匿名用户的密码可为空,其实也可以任意输入,随便输一个就可以了
这里贴出FileUtil用于文件拷贝,考虑到会重用这部分代码,因此构建一个工具类
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileUtil { /** * 文件拷贝,通过对流的操作完成 * * @param insm * @param outsm * @throws IOException */ public static void copyFile(InputStream insm, OutputStream outsm) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(insm); bos = new BufferedOutputStream(outsm); byte[] b = new byte[8192]; int readBytes = -1; while ((readBytes = bis.read(b)) != -1) { bos.write(b, 0, readBytes); } } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } }
方法一:通过URL实现FTP文件上传
//本地需要上传的文件 File needToBeUpload = new File("E:\\References\\Java_Web开发总览.pdf"); InputStream ins = new FileInputStream(needToBeUpload); URL url = new URL("ftp://@192.168.30.190/xxx.pdf"); URLConnection conn = url.openConnection(); OutputStream outs = conn.getOutputStream(); FileUtil.copyFile(ins, outs);
方法二:通过sun.net.ftp.FtpClient类实现FTP文件上传
FtpClient ftpClient = new FtpClient(); ftpClient.openServer("192.168.30.190", 21); ftpClient.login("anonymous", "anonymous"); ftpClient.binary(); TelnetOutputStream outs = ftpClient.put("xxx.pdf"); FileUtil.copyFile(ins, outs);
这里的匿名用户,密码可以为空,可以随便填写