JAVA實現文件下載 , 文件刪除

 /**
     * @param filePath 文件將要保存的目錄
     * @param url      請求的路徑
     * @return
     * @從制定URL下載文件並保存到指定目錄
     */
    public static boolean saveUrlAs(String url, String filePath) {


        int byteRead;

            try {
                // 建立鏈接
                URL httpUrl = new URL(url);
                //2.獲取鏈接
                URLConnection conn = httpUrl.openConnection();
                //3.輸入流
                InputStream inStream = conn.getInputStream();
                //3.寫入文件
                FileOutputStream fs = new FileOutputStream(filePath);

                byte[] buffer = new byte[1024];
                while ((byteRead = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteRead);
                }
                inStream.close();
                fs.close();
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

    }


   /**
     * 文件刪除
     * @param fileName 文件目錄+名稱
     * @return
     */
     public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路徑所對應的文件存在,並且是一個文件,則直接刪除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("刪除單個文件" + fileName + "成功!");
                return true;
            } else {
                System.out.println("刪除單個文件" + fileName + "失敗!");
                return false;
            }
        } else {
            System.out.println("刪除單個文件失敗:" + fileName + "不存在!");
            return false;
        }
    }


    public static void main(String[] args) {
        String mp4Url = "https://admincdn.52tzgame.com/huodong_muban/o_1dpjv2g2bi4822n1s0pu301ohc2m.mp4";   //文件URL地址
        String fileName = "o_1dpjv2g2bi4822n1s0pu301ohc2m.mp4";     //爲下載的文件命名
        String filePath = "D:\\";      //保存目錄
        saveUrlAs(mp4Url, filePath + fileName);
        deleteFile(filePath+fileName);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章