java 下载功能

java 下载功能,第1张

下载功能实际上就是将远程服务器文件流通过ftp功能转换为本地文件流进行存储。举例:

/**

*下载并解压文件

*

* @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方法中的用户名和密码即可进行远程服务器连接下载,具体的根据实际情况修改即可。

strUrl为文件地址,fileName为文件在本地的保存路首祥径,试试吧~

public static void writeFile(String strUrl, String fileName) {

URL url = null

try {

url = new URL(strUrl)

} catch (MalformedURLException e2) {

e2.printStackTrace()

}

InputStream is = null

try {

is = url.openStream()

} catch (IOException e1) {

e1.printStackTrace()

}

OutputStream os = null

try {

os = new FileOutputStream( fileName)

int bytesRead = 0

byte[] buffer = new byte[8192]

while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {

os.write(buffer, 0, bytesRead)

}

System.out.println("者岁搏下载雀谈成功:"+strUrl)

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12255023.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存