Java从FTP服务器上传下载文件的代码
jopen
11年前
import java.io.*; import java.util.*; import java.sql.*; import java.net.Socket; import java.net.ServerSocket; import java.net.InetAddress; import sun.net.ftp.*; import sun.net.TelnetInputStream; import sun.net.TelnetOutputStream; /* * 用于连接到FTP服务器上 * @return String 若失败则返回失败信息,成功返回空字符串 */ private String connectToFtpServer(){ if ((this.ftpserver==null)||(this.ftpserver.equals(""))) return "FTP服务器名设置不正确!"; try{ fc.openServer(this.ftpserver); fc.login(this.ftpuser,this.ftppwd); fc.ascii(); }catch(FtpLoginException e){ return "没有与FTP服务器连接的权限,或用户名密码设置不正确!"; }catch(IOException e){ return "与FTP服务器连接失败!"; }catch(SecurityException e){ return "没有权限与FTP服务器连接"; } return ""; } /* * 用于关闭与FTP服务器的连接 */ private void closeFtpConnect(){ if (fc.serverIsOpen()){ try{ fc.closeServer(); }catch(Exception e){ }finally{ fc = null; } } } public String downloadFile(String fileName){ //只下载文本文件或XML文件 if (!this.isTextFile(fileName)) return fileName + "不是XML文件或文本文件"; String retMessage = ""; if (!fc.serverIsOpen()){ retMessage = this.connectToFtpServer(); if (!retMessage.equals("")) return "下载文件:" + fileName + "时无法和FTP服务器连接"; } //if (conn == null) return "下载文件:" + fileName + "时无法连接到数据库"; String chkSql = "select 1 from t_trans_log where file_name = '" + fileName + "'"; if (sqlbean.checkQueryRowCount(chkSql) > 0) return retMessage; if (this.dldir==null) this.dldir = ""; try{ TelnetInputStream is = fc.get(this.dldir + "/" + fileName); BufferedReader br = new BufferedReader(new InputStreamReader(is)); //读取文件内容到stringbuffer StringBuffer sb = new StringBuffer(); int length; char buffer[] = new char[1]; while((length = br.read(buffer,0,1)) != -1) sb.append(buffer); //构造sql语句插入记录 //String ls_lsh = get_lsh(12); String ls_lsh = ah.getAutoID("xf_lsh",12); String ls_sql = "insert into t_trans_log(tran_id,tran_flag,file_name,file_content)values('" ls_sql += ls_lsh + "','0','" + fileName + "','" + sb.toString() + "')"; conn = connmanager.getConnection(); conn.setAutoCommit(false); sqlbean.executeUpdate(conn,ls_sql); //将stringbuffer写入文件中 byte buf[] = sb.toString().getBytes(); OutputStream f1 = new FileOutputStream(this.bdldir + "/" + fileName); f1.write(buf); f1.close(); is.close(); br.close(); //删除文件 this.deleteFile(this.dldir + "/" + fileName); conn.commit(); conn.setAutoCommit(true); connmanager.close(conn); }catch(SQLException e){ retMessage = "下载文件:" + fileName + "时发生数据库错误:" + e.getMessage(); }catch(IOException e){ retMessage = "下载文件:" + fileName + "时发生文件读写错误:" + e.getMessage(); } return retMessage; } //下载指定目录下的所有文件 public String downloadFiles(String dirName){ String retMessage = ""; if ((dirName == null)||(dirName.equals(""))) dirName = this.dldir; String[] sa = this.list(); for (int i = 0;i < sa.length;i++){ retMessage = this.downloadFile(sa[i]); if (!retMessage.equals("")) return retMessage; } return retMessage; } //下载FTP服务器上的所有文件 public String downloadFiles(){ return downloadFiles(this.dldir); } public String uploadFile(String fileName){ String retMessage = ""; if (!fc.serverIsOpen()){ retMessage = this.connectToFtpServer(); if (!retMessage.equals("")) return "上传文件:" + fileName + "时无法和FTP服务器连接"; } //if (conn == null) return "上传文件:" + fileName + "时无法连接到数据库"; //String chkSql = "select 1 from t_trans_log where file_name = '" + fileName + "'"; //if (Utils.checkQueryRowCount(conn,chkSql) > 0) return retMessage; try{ if (this.uldir==null) this.uldir = ""; if (this.buldir==null) this.buldir = ""; TelnetOutputStream os = fc.put(this.uldir + "/" + fileName); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os)); StringBuffer sb = new StringBuffer(); InputStream f1 = new FileInputStream(this.buldir + "/" + fileName); int size = f1.available(); byte b[] = new byte[size]; while(f1.read(b)!= -1) sb.append(new String(b,0,b.length)); //构造sql语句插入记录 //String ls_sql = "insert into t_trans_log(tran_id,file_name,file_content)values('" + get_lsh(12) + "','" + fileName + "','" + sb.toString() + "')"; String ls_sql = "insert into t_trans_log(tran_id,file_name,file_content)values('" + ah.getAutoID("xf_lsh",12) + "','" + fileName + "','" + sb.toString() + "')"; conn = connmanager.getConnection(); conn.setAutoCommit(false); sqlbean.executeUpdate(conn,ls_sql); //写入文件 wr.write(sb.toString()); f1.close(); wr.close(); os.close(); //删除本地文件 File ls_file = new File(this.buldir + "/" + fileName); ls_file.delete(); conn.commit(); conn.setAutoCommit(true); connmanager.close(conn); }catch(SQLException e){ retMessage = "上传文件:" + fileName + "时发生数据库错误:" + e.getMessage(); }catch(IOException e){ retMessage = "上传文件:" + fileName + "时发生文件读写错误:" + e.getMessage(); } return retMessage; } /** * 功能:获取指定目录文件列表并上传每一个文件 */ public String uploadFiles(){ String retMessage = ""; if (this.buldir == null) this.buldir = ""; File ls_file = new File(this.buldir); File[] entries = ls_file.listFiles(); for(int i=0; i this.uploadFile(entries[i].getName()); if (!retMessage.equals("")) return retMessage; } return retMessage; } public String deleteFile(String fileName){ String retMessage = ""; try{ Socket socket = new Socket(this.ftpserver,this.ftpport); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (!reader.readLine().startsWith("220")) return "DELE 无法连接到指定的FTP服务器"; Writer writer = new OutputStreamWriter(socket.getOutputStream()); writer.write("USER " + this.ftpuser + "rn"); writer.flush(); if (!reader.readLine().startsWith("331")) return "DELE 指定的登录FTP用户名无效"; writer.write("PASS " + this.ftppwd + "rn"); writer.flush(); if (!reader.readLine().startsWith("230")) return "DELE FTP用户的登录口令错误"; writer.write("DELE " + fileName + "rn"); writer.flush(); if (!reader.readLine().startsWith("250")) return "无法删除指定文件" + fileName; writer.close(); reader.close(); socket.close(); }catch(Exception e){ retMessage = "删除文件" + fileName + "时发生错误" + e.getMessage(); } return retMessage; } /** * 功能:获取指定目录下以分号分隔的文件名列表 */ public String getDownloadFileList(String dirName){ StringBuffer sb = new StringBuffer(); String[] sa = list(dirName); int saLength = sa.length; for (int i = 0; i < saLength; i++) sb.append(sa[i]).append(";"); return sb.toString(); } /** * 功能:获取默认下载目录下以分号分隔的文件名列表 */ public String getDownloadFileList(){ return getDownloadFileList(this.dldir); } /** * 功能:以数组的形式返回服务器上指定目录下的文件名列表 */ public String[] list(String dirName){ String[] fileNameList = new String[0]; Vector lines = new Vector(); String line = null; if (fc.serverIsOpen()){ try{ fc.cd(dirName.equals("")?this.dldir:dirName); TelnetInputStream ins = fc.list(); fc.cd("/"); LineNumberReader in = new LineNumberReader(new InputStreamReader(ins)); line = in.readLine(); while((line != null)&&!(line.trim().equals(""))&&!(line.trim().equals("/n"))){ lines.add(line.substring(line.lastIndexOf(" ") + 1,line.length())); line = in.readLine(); } in.close(); ins.close(); }catch(Exception e){ } if (!lines.isEmpty()) fileNameList = (String[])lines.toArray(fileNameList); } return fileNameList; } /** * 功能:以数组的形式返回服务器上默认下载目录下的文件名列表 */ public String[] list(){ return this.list(this.dldir); } public String getDlDir(){return this.dldir;} /** * 功能:用于判断文件是否是XML或TXT文件 */ private boolean isTextFile(String fileName){ return (fileName.toLowerCase().endsWith(".xml")||fileName.toLowerCase().endsWith(".txt")); } }