/**
*下载并解压文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null
ByteArrayOutputStream bos = null
FileOutputStream fos = null
FTPClient ftpClient = new FTPClient()
String SFP = System.getProperty("file.separator")
String bl = "false"
try {
Log.info("下载并解密文件开始")
Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22)
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22)
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD)
FTPFile[] fs
ftpClient.makeDirectory(routeFilepath)
ftpClient.changeWorkingDirectory(routeFilepath)
bl = "false"
fs = ftpClient.listFiles()
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true"
Log.info("下载文件开始。")
ftpClient.setBufferSize(1024)
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)
InputStream is = ftpClient.retrieveFileStream(fileName)
bos = new ByteArrayOutputStream(is.available())
byte[] buffer = new byte[1024]
int count = 0
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count)
}
bos.flush()
fos = new FileOutputStream(localFilePath+SFP+fileName)
fos.write(bos.toByteArray())
Log.info("下载文件结束:"+localFilePath)
}
}
Log.info("检查文件是否存:"+fileName+" "+bl)
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。")
return bl
}
return bl
} catch (Exception e) {
throw e
} finally {
if (fis != null) {
try {
fis.close()
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e)
}
}
if (bos != null) {
try {
bos.close()
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e)
}
}
if (fos != null) {
try {
fos.close()
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e)
}
}
}
}
备注:只需要修改 ftpClient.connect方法中的用户名和密码即可进行远程服务器连接下载,具体的根据实际情况修改即可。
java编程方法下载服务器上的文件到本地客服端,代码如下:
import java.io.BufferedWriterimport java.io.File
import java.io.FileOutputStream
import java.io.FileWriter
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.net.URLConnection
public class DownLoad {
public static void downloadFile(URL theURL, String filePath) throws IOException {
File dirFile = new File(filePath)
if(!dirFile.exists()){
//文件路径不存在时,自动创建目录
dirFile.mkdir()
}
//从服务器上获取图片并保存
URLConnection connection = theURL.openConnection()
InputStream in = connection.getInputStream()
FileOutputStream os = new FileOutputStream(filePath+"\\123.png")
byte[] buffer = new byte[4 * 1024]
int read
while ((read = in.read(buffer)) > 0) {
os.write(buffer, 0, read)
}
os.close()
in.close()
}
public static void main(String[] args) {
//下面添加服务器的IP地址和端口,以及要下载的文件路径
String urlPath = "http://服务器IP地址:端口/image/123.png"
//下面代码是下载到本地的位置
String filePath = "d:\\excel"
URL url = new URL(urlPath)
try {
downloadFile(url,filePath)
} catch (IOException e) {
e.printStackTrace()
}
}
}