簡體   English   中英

Java http - 讀取大文件

[英]Java http - read large file

我正在使用http訪問在Java程序中讀取一個大文件。 我閱讀了流,然后我應用了一些標准。 是否可以在讀取流上應用標准,因此我將得到一個輕量級結果(我正在閱讀大文件)?

這是我讀取文件的代碼:

public String getMyFileContent(URLConnection uc){
            String myresult = null;
            try {
                InputStream is = uc.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                int numCharsRead;
                char[] charArray = new char[1024];
                StringBuffer sb = new StringBuffer();

                while ((numCharsRead = isr.read(charArray)) > 0) {
                    sb.append(charArray, 0, numCharsRead);
                }
                myresult = sb.toString();

            }
            catch (MalformedURLException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return result;  
}

然后在另一種方法中,我應用標准(解析內容)。 我不能這樣做:

public String getMyFileContent(URLConnection uc){
    String myresult = null;
    try {
        InputStream is = uc.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();

        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
            //Apply my criteria here on the stream ??? Is it possible ???
        }
        myresult = sb.toString();
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return myresult;
}

我將使用的模板是

InputStreamReader isr = new InputStreamReader(uc.getInputStream());
int numCharsRead;
char[] charArray = new char[1024];

while ((numCharsRead = isr.read(charArray)) > 0) {
    //Apply my criteria here on the stream
}

但是因為它是文本,所以這可能更有用

InputStream is = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String line;

while ((line = br.readLine()) != null) {
    //Apply my criteria here on each line
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM