简体   繁体   English

Java http - 读取大文件

[英]Java http - read large file

I am reading a big file in a Java program, using http access. 我正在使用http访问在Java程序中读取一个大文件。 I read the stream, and then I apply some criteria. 我阅读了流,然后我应用了一些标准。 Would it be possible to apply the criteria on the read stream, so I will have a light result (I'm reading big files)? 是否可以在读取流上应用标准,因此我将得到一个轻量级结果(我正在阅读大文件)?

Here is my code for reading the file: 这是我读取文件的代码:

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;  
}

And in another method, I then apply the criteria (to parse the content). 然后在另一种方法中,我应用标准(解析内容)。 I couldn't achieve to do like this: 我不能这样做:

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;
}

The template I would use is 我将使用的模板是

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
}

however since it is text, this might be more useful 但是因为它是文本,所以这可能更有用

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