JAVA下載、刪除、修改檔名、
阿新 • • 發佈:2019-02-07
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、修改檔名
3、刪除檔案/** * 修改檔名字 * @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; } }
/** * 刪除檔案 * @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(); }