java讀取url中的txt文件

我涉及到的項目中場景是這樣的:要把腦電數據(txt文件)從阿里雲oss中解析成json,爲了不產生文件冗餘,就不下載了。

我之前對輸入流輸出流什麼的,用的不多,不太熟悉。所以這次寫完記錄一下。網上查了有下載的代碼,有解析的代碼,就是沒有直接讀取,不下載的代碼。其實就是用connection連接,獲得輸入流,再用循環的方式讀取。

public class Jxtxt {
    public static void main(String[] args) {
        //文件下載
        String photoUrl="你的txt的網絡地址";
        String result= saveUrlAs(photoUrl, "GET");
        System.out.println(result);
    }


    public static String saveUrlAs(String url,String method){
        String result;
        StringBuffer resultBuffer=new StringBuffer();

   
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try
        {
            // 建立鏈接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表單,默認get方式
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用緩存
            conn.setUseCaches(false);
            //連接指定的資源
            conn.connect();
            //獲取網絡輸入流
            inputStream=conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //設定每次讀取的字節大小
            byte[] buf = new byte[4096];
            //計算按字節大小讀取需要的行數
            int length = bis.read(buf);
            //while循環讀取存入resultBuffer
            while(length != -1)
            {
                String str = new String(buf, 0, length);
                resultBuffer.append(str);
            }
            //依次關閉資源
            bis.close();
            inputStream.close();
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        result=resultBuffer.toString();
        return result;

    }

}

可惜的是,這個東西沒用上,因爲腦電數據11k左右,太大了。不合適。

之前沒了解,今天看源碼才瞭解這裏的byte幹什麼用的。。。。慚愧。

關於爲什麼用BufferInputStream,這裏有一個標準的答案。

InputStream:每次從硬盤讀入一個字到中轉站, 再寫入目的文件(硬盤)

BufferStream:一次讀入n個字節到輸入緩衝區,接着經中轉站一個個寫入到輸出緩衝區,輸入緩衝區爲空時再次從硬盤讀入批量數據,同理輸出緩衝區滿了以後再批量寫入到目的文件(硬盤)。(https://blog.csdn.net/weixin_42130471/article/details/82914013 原文有錯別字)

發佈了7 篇原創文章 · 獲贊 3 · 訪問量 1007
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章