首頁 > 軟體

Java讀取網路檔案的範例程式碼

2022-07-12 14:00:47

Java讀取網路檔案

輸入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; // 伺服器返回的狀態
        String ee = new String();
        try
        {
            URL url =new URL(filePath); // 建立URL
            URLConnection urlconn = url.openConnection(); // 試圖連線並取得返回狀態碼
            urlconn.connect();
            HttpURLConnection httpconn =(HttpURLConnection)urlconn;
            HttpResult = httpconn.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("無法連線到");
            } else {
                int filesize = urlconn.getContentLength(); // 取資料長度
                InputStreamReader isReader = new InputStreamReader(urlconn.getInputStream(),"UTF-8");
                BufferedReader reader = new BufferedReader(isReader);
                StringBuffer buffer = new StringBuffer();
                String line; // 用來儲存每行讀取的內容
                line = reader.readLine(); // 讀取第一行
                while (line != null) { // 如果 line 為空說明讀完了
                    buffer.append(line); // 將讀到的內容新增到 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讀取網路檔案問題 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");

這樣會報這個錯誤

應該是雙斜槓才正確

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com