您的位置:首页 > 编程语言 > Java开发

JAVA下载、删除、修改文件名、

2018-01-25 15:00 369 查看
JAVA文件的下载

/**
* 下载文件
*
* @param savepath 保存路径
* @param resurl 资源路径
* @param fileName 自定义资源名
*/
public String getInternetRes(String savepath, String resurl, String fileName) {
URL url = null;
HttpURLConnection con = null;
InputStream in = null;
FileOutputStream out = null;
File res = null;
try {
url = new URL(resurl);
//建立http连接,得到连接对象
con = (HttpURLConnection) url.openConnection();
in = con.getInputStream();
byte[] data = getByteData(in);//转化为byte数组

File file = new File(savepath);
if (!file.exists()) {
file.mkdirs();
}

res = new File(file + File.separator + fileName);
out = new FileOutputStream(res);
out.write(data);
logger.info("downloaded successfully!!!");
} catch (IOException e) {
logger.error(e.getMessage() , e);
} finally {
try {
if (null != out)
out.close();
if (null != in)
in.close();
} catch (IOException e) {
logger.error(e.getMessage() , e);
}
}

return res.toString();
}

/**
* 从输入流中获取字节数组
*
* @param in
* @return
* @throws IOException
*/
private byte[] getByteData(InputStream in) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(b)) != -1) {
bos.write(b, 0, len);
}
if(null!=bos){
bos.close();
}
return bos.toByteArray();
}
2、修改文件名

/**
* 修改文件名字
* @param filePath 文件路径
* @param newName 新的文件名
* @return
*/
public boolean updateFileName(String filePath , String newName){
File f = new File(filePath);
String c = f.getParent();
File mm = new File(c + sb.toString());
if (f.renameTo(mm)) {
return true;
} else {
return false;
}
}3、删除文件
/**
* 删除文件
* @param filePath 文件路径
* @param format 文件后缀
*/
public void deleteFile(String filePath , String format){
StringBuffer sb = new StringBuffer(filePath);
sb.append(format);
File f = new File(sb.toString());
if(f.exists())
f.delete();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: