Java讀取網站需下載的檔案
阿新 • • 發佈:2019-02-06
為什麼會產生這樣一個需求,原因是使用者想讀取Oracle資料庫儲存的BLOB欄位的值。但是直接在資料層面我又不會操作將其匯出.BLOB儲存著各種型別的檔案。而頁面正好有下載需要的連線,後來一想,就讀連線把資料寫出來。
直接上程式碼。在D盤放了cross檔案,裡面存放的是需要讀取的檔名,檔名是按行放的,因為讀取的時候時按行讀的。
然後main方法一執行就OK了。
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownLoadFiles {
public static void main(String[] args){
FileInputStream in = null;
BufferedReader reader=null ;
try {
System.out.println("以行為單位讀取檔案內容,一次讀一整行:");
in=new FileInputStream("D://cross.txt");
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String paths = null;
int line = 1;
// 一次讀入一行,直到讀入null為檔案結束
while ((paths = reader.readLine()) != null) {
String pn = URLEncoder.encode(paths, "utf-8"); //防止有空格,Server returned HTTP response code: 505
try {
SendGET("http://XXXX:9083/isp/attach/download.do","filePath=/knowledge_manager/"+pn,paths);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("line " + line + ": " + paths);
line++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void SendGET(String url,String param,String paths) throws Exception{
try {
//建立url
URL realurl=new URL(url+"?"+param);
//開啟連線
URLConnection connection=realurl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//建立連線
connection.connect();
InputStream inStream = connection.getInputStream();
byte[] data = readInputStream(inStream);
File imageFile = new File("D:" + File.separator + paths);
//建立輸出流
FileOutputStream outStream = new FileOutputStream(imageFile);
//寫入資料
outStream.write(data);
//關閉輸出流
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//建立一個Buffer字串
byte[] buffer = new byte[1024];
//每次讀取的字串長度,如果為-1,代表全部讀取完畢
int len = 0;
//使用一個輸入流從buffer裡把資料讀取出來
while( (len=inStream.read(buffer)) != -1 ){
//用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度
outStream.write(buffer, 0, len);
}
//關閉輸入流
inStream.close();
//把outStream裡的資料寫入記憶體
return outStream.toByteArray();
}
}