Java讀取網(wǎng)絡(luò)文件的實例代碼
更新時間:2022年07月12日 11:28:49 作者:CrazZy651314
這篇文章主要介紹了Java讀取網(wǎng)絡(luò)文件的實例代碼,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
Java讀取網(wǎng)絡(luò)文件
輸入url地址讀取txt文件
/** * Created by qqg on 2018/1/3. */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class w{ private static String openFile(String filePath) { int HttpResult; // 服務(wù)器返回的狀態(tài) String ee = new String(); try { URL url =new URL(filePath); // 創(chuàng)建URL URLConnection urlconn = url.openConnection(); // 試圖連接并取得返回狀態(tài)碼 urlconn.connect(); HttpURLConnection httpconn =(HttpURLConnection)urlconn; HttpResult = httpconn.getResponseCode(); if(HttpResult != HttpURLConnection.HTTP_OK) { System.out.print("無法連接到"); } else { int filesize = urlconn.getContentLength(); // 取數(shù)據(jù)長度 InputStreamReader isReader = new InputStreamReader(urlconn.getInputStream(),"UTF-8"); BufferedReader reader = new BufferedReader(isReader); StringBuffer buffer = new StringBuffer(); String line; // 用來保存每行讀取的內(nèi)容 line = reader.readLine(); // 讀取第一行 while (line != null) { // 如果 line 為空說明讀完了 buffer.append(line); // 將讀到的內(nèi)容添加到 buffer 中 buffer.append(" "); // 添加換行符 line = reader.readLine(); // 讀取下一行 } System.out.print(buffer.toString()); ee = buffer.toString(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ee; } public static void main(String[] args){ System.out.print(w.openFile("http://******/hrmsstatic/SensitiveWord.txt")); } }
Java讀取網(wǎng)絡(luò)文件問題 protocol = http host = null
通過ip地址讀取文件
public void testReadFile() { ?? ??? ?try { ?? ??? ??? ?URL url = new URL("http://172.31.77.220:8080/data/files/F_000001/F_000001_10743.xlsx"); ?? ??? ??? ?URLConnection openConnection = url.openConnection(); ?? ??? ??? ?InputStream inputStream = openConnection.getInputStream(); ?? ??? ?} catch (Exception e) { ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} ?? ?}
protocol = http host = null錯誤
上述代碼寫成
URL url = new URL("http:/172.31.77.220:8080/data/files/F_000001/F_000001_10743.xlsx");
這樣會報這個錯誤
應(yīng)該是雙斜杠才正確
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Javadoc標(biāo)簽和Javadoc注釋規(guī)范說明
這篇文章主要介紹了Javadoc標(biāo)簽和Javadoc注釋規(guī)范說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02