[Java]遠端下載檔案並讀取例項方法
阿新 • • 發佈:2019-02-01
簡單的檔案下載後讀取顯示,該方法可返回內容的結果集。一般適用於文字文件的下載,以供學習交流。
/** * 遠端下載檔案並讀取返回p * @param filePath 檔案網路地址 如http://www.baidu.com/1.txt * @return String */ public String DownAndReadFile(String filePath){ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); File savePath = new File("D://"+date);//建立新檔案 if (!savePath.exists()) { savePath.mkdir(); } String[] urlname = filePath.split("/"); int len = urlname.length-1; String uname = urlname[len];//獲取檔名 try { File file = new File(savePath+"//"+uname);//建立新檔案 if(file!=null && !file.exists()){ file.createNewFile(); } OutputStream oputstream = new FileOutputStream(file); URL url = new URL(filePath); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoInput(true);//設定是否要從 URL 連線讀取資料,預設為true uc.connect(); InputStream iputstream = uc.getInputStream(); System.out.println("file size is:"+uc.getContentLength());//列印檔案長度 byte[] buffer = new byte[4*1024]; int byteRead = -1; while((byteRead=(iputstream.read(buffer)))!= -1){ oputstream.write(buffer, 0, byteRead); } oputstream.flush(); iputstream.close(); oputstream.close(); //讀取檔案 StringBuffer strb = new StringBuffer(); FileInputStream fs = new FileInputStream(new File(savePath+"//"+uname)); InputStreamReader isr = new InputStreamReader(fs,"UTF-8"); BufferedReader br = new BufferedReader(isr); String data = ""; while((data = br.readLine()) != null){ strb.append(data + "\n"); } br.close(); fs.close(); isr.close(); System.out.println(strb.toString()); return strb.toString(); } catch (Exception e) { System.out.println("讀取失敗!"); e.printStackTrace(); } return null; }