java使用apache commons连接ftp修改ftp文件名失败原因
今天被ftp上中文名修改坑了好久
项目用的是apachecommons里的FtpClient实现的对ftp文件的上传下载操作,今天增加了业务要修改ftp上的文件名,然后就一直的报错,问题是它修改名字的方法只返回一个boolean,没有异常,这就很蛋疼了,找了好久才发现是中文的名字的原因
改名
直接上代码
packagenet.codejava.ftp; importjava.io.IOException; importorg.apache.commons.net.ftp.FTPClient; publicclassFTPRenamer{ publicstaticvoidmain(String[]args){ Stringserver="www.ftpserver.com"; intport=21; Stringuser="username"; Stringpass="password"; FTPClientftpClient=newFTPClient(); try{ ftpClient.connect(server,port); ftpClient.login(user,pass); //renamingdirectory StringoldDir="/photo"; StringnewDir="/photo_2012"; booleansuccess=ftpClient.rename(oldDir,newDir); if(success){ System.out.println(oldDir+"wassuccessfullyrenamedto:" +newDir); }else{ System.out.println("Failedtorename:"+oldDir); } //renamingfile StringoldFile="/work/error.png"; StringnewFile="/work/screenshot.png"; success=ftpClient.rename(oldFile,newFile); if(success){ System.out.println(oldFile+"wassuccessfullyrenamedto:" +newFile); }else{ System.out.println("Failedtorename:"+oldFile); } ftpClient.logout(); ftpClient.disconnect(); }catch(IOExceptionex){ ex.printStackTrace(); }finally{ if(ftpClient.isConnected()){ try{ ftpClient.logout(); ftpClient.disconnect(); }catch(IOExceptionex){ ex.printStackTrace(); } } } } } 如果修改的名字里没有中文,用上面的代码就够了,但如果有中文就要对文件名进行转码了,转码代码如下 //renamingfile StringoldFile="/work/你好.png"; StringnewFile="/work/世界.png"; success=ftpClient.rename( newString(oldFile.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1), newString(newFile.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1) );
这样再修改名字就没有问题了
顺便记录一下上传、下载、删除、检查文件是否存在, 同样的,如果有中文名,最好先转一下码再进行操作
上传
importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importorg.apache.commons.net.ftp.FTP; importorg.apache.commons.net.ftp.FTPClient; /** *Aprogramthatdemonstrateshowtouploadfilesfromlocalcomputer *toaremoteFTPserverusingApacheCommonsNetAPI. *@authorwww.codejava.net */ publicclassFTPUploadFileDemo{ publicstaticvoidmain(String[]args){ Stringserver="www.myserver.com"; intport=21; Stringuser="user"; Stringpass="pass"; FTPClientftpClient=newFTPClient(); try{ ftpClient.connect(server,port); ftpClient.login(user,pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //APPROACH#1:uploadsfirstfileusinganInputStream FilefirstLocalFile=newFile("D:/Test/Projects.zip"); StringfirstRemoteFile="Projects.zip"; InputStreaminputStream=newFileInputStream(firstLocalFile); System.out.println("Startuploadingfirstfile"); booleandone=ftpClient.storeFile(firstRemoteFile,inputStream); inputStream.close(); if(done){ System.out.println("Thefirstfileisuploadedsuccessfully."); } //APPROACH#2:uploadssecondfileusinganOutputStream FilesecondLocalFile=newFile("E:/Test/Report.doc"); StringsecondRemoteFile="test/Report.doc"; inputStream=newFileInputStream(secondLocalFile); System.out.println("Startuploadingsecondfile"); OutputStreamoutputStream=ftpClient.storeFileStream(secondRemoteFile); byte[]bytesIn=newbyte[4096]; intread=0; while((read=inputStream.read(bytesIn))!=-1){ outputStream.write(bytesIn,0,read); } inputStream.close(); outputStream.close(); booleancompleted=ftpClient.completePendingCommand(); if(completed){ System.out.println("Thesecondfileisuploadedsuccessfully."); } }catch(IOExceptionex){ System.out.println("Error:"+ex.getMessage()); ex.printStackTrace(); }finally{ try{ if(ftpClient.isConnected()){ ftpClient.logout(); ftpClient.disconnect(); } }catch(IOExceptionex){ ex.printStackTrace(); } } } }
下载
importjava.io.BufferedOutputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importorg.apache.commons.net.ftp.FTP; importorg.apache.commons.net.ftp.FTPClient; /** *Aprogramdemonstrateshowtouploadfilesfromlocalcomputertoaremote *FTPserverusingApacheCommonsNetAPI. *@authorwww.codejava.net */ publicclassFTPDownloadFileDemo{ publicstaticvoidmain(String[]args){ Stringserver="www.myserver.com"; intport=21; Stringuser="user"; Stringpass="pass"; FTPClientftpClient=newFTPClient(); try{ ftpClient.connect(server,port); ftpClient.login(user,pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //APPROACH#1:usingretrieveFile(String,OutputStream) StringremoteFile1="/test/video.mp4"; FiledownloadFile1=newFile("D:/Downloads/video.mp4"); OutputStreamoutputStream1=newBufferedOutputStream(newFileOutputStream(downloadFile1)); booleansuccess=ftpClient.retrieveFile(remoteFile1,outputStream1); outputStream1.close(); if(success){ System.out.println("File#1hasbeendownloadedsuccessfully."); } //APPROACH#2:usingInputStreamretrieveFileStream(String) StringremoteFile2="/test/song.mp3"; FiledownloadFile2=newFile("D:/Downloads/song.mp3"); OutputStreamoutputStream2=newBufferedOutputStream(newFileOutputStream(downloadFile2)); InputStreaminputStream=ftpClient.retrieveFileStream(remoteFile2); byte[]bytesArray=newbyte[4096]; intbytesRead=-1; while((bytesRead=inputStream.read(bytesArray))!=-1){ outputStream2.write(bytesArray,0,bytesRead); } success=ftpClient.completePendingCommand(); if(success){ System.out.println("File#2hasbeendownloadedsuccessfully."); } outputStream2.close(); inputStream.close(); }catch(IOExceptionex){ System.out.println("Error:"+ex.getMessage()); ex.printStackTrace(); }finally{ try{ if(ftpClient.isConnected()){ ftpClient.logout(); ftpClient.disconnect(); } }catch(IOExceptionex){ ex.printStackTrace(); } } } }
删除
importjava.io.IOException; importorg.apache.commons.net.ftp.FTPClient; importorg.apache.commons.net.ftp.FTPReply; publicclassFTPDeleteFileDemo{ publicstaticvoidmain(String[]args){ Stringserver="www.myserver.com"; intport=21; Stringuser="user"; Stringpass="pass"; FTPClientftpClient=newFTPClient(); try{ ftpClient.connect(server,port); intreplyCode=ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(replyCode)){ System.out.println("Connectfailed"); return; } booleansuccess=ftpClient.login(user,pass); if(!success){ System.out.println("Couldnotlogintotheserver"); return; } StringfileToDelete="/repository/video/cool.mp4"; booleandeleted=ftpClient.deleteFile(fileToDelete); if(deleted){ System.out.println("Thefilewasdeletedsuccessfully."); }else{ System.out.println("Couldnotdeletethefile,itmaynotexist."); } }catch(IOExceptionex){ System.out.println("Ohno,therewasanerror:"+ex.getMessage()); ex.printStackTrace(); }finally{ //logsoutanddisconnectsfromserver try{ if(ftpClient.isConnected()){ ftpClient.logout(); ftpClient.disconnect(); } }catch(IOExceptionex){ ex.printStackTrace(); } } } }
检查文件/文件夹是否存在
packagenet.codejava.ftp; importjava.io.IOException; importjava.io.InputStream; importjava.net.SocketException; importorg.apache.commons.net.ftp.FTPClient; importorg.apache.commons.net.ftp.FTPReply; /** *Thisprogramdemonstrateshowtodetermineexistenceofaspecific *file/directoryonaremoteFTPserver. *@authorwww.codejava.net * */ publicclassFTPCheckFileExists{ privateFTPClientftpClient; privateintreturnCode; /** *Determineswhetheradirectoryexistsornot *@paramdirPath *@returntrueifexists,falseotherwise *@throwsIOExceptionthrownifanyI/Oerroroccurred. */ booleancheckDirectoryExists(StringdirPath)throwsIOException{ ftpClient.changeWorkingDirectory(dirPath); returnCode=ftpClient.getReplyCode(); if(returnCode==550){ returnfalse; } returntrue; } /** *Determineswhetherafileexistsornot *@paramfilePath *@returntrueifexists,falseotherwise *@throwsIOExceptionthrownifanyI/Oerroroccurred. */ booleancheckFileExists(StringfilePath)throwsIOException{ InputStreaminputStream=ftpClient.retrieveFileStream(filePath); returnCode=ftpClient.getReplyCode(); if(inputStream==null||returnCode==550){ returnfalse; } returntrue; } /** *ConnectstoaremoteFTPserver */ voidconnect(Stringhostname,intport,Stringusername,Stringpassword) throwsSocketException,IOException{ ftpClient=newFTPClient(); ftpClient.connect(hostname,port); returnCode=ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(returnCode)){ thrownewIOException("Couldnotconnect"); } booleanloggedIn=ftpClient.login(username,password); if(!loggedIn){ thrownewIOException("Couldnotlogin"); } System.out.println("Connectedandloggedin."); } /** *Logsoutanddisconnectsfromtheserver */ voidlogout()throwsIOException{ if(ftpClient!=null&&ftpClient.isConnected()){ ftpClient.logout(); ftpClient.disconnect(); System.out.println("Loggedout"); } } /** *Runsthisprogram */ publicstaticvoidmain(String[]args){ Stringhostname="www.yourserver.com"; intport=21; Stringusername="your_user"; Stringpassword="your_password"; StringdirPath="Photo"; StringfilePath="Music.mp4"; FTPCheckFileExistsftpApp=newFTPCheckFileExists(); try{ ftpApp.connect(hostname,port,username,password); booleanexist=ftpApp.checkDirectoryExists(dirPath); System.out.println("Isdirectory"+dirPath+"exists?"+exist); exist=ftpApp.checkFileExists(filePath); System.out.println("Isfile"+filePath+"exists?"+exist); }catch(IOExceptionex){ ex.printStackTrace(); }finally{ try{ ftpApp.logout(); }catch(IOExceptionex){ ex.printStackTrace(); } } } }
参考
https://www.codejava.net/java-se/ftp/how-to-start-ftp-programming-with-java
总结
以上所述是小编给大家介绍的java使用apachecommons连接ftp修改ftp文件名失败原因,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!