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

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();
    }













  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值