gpt4 book ai didi

Java http-读取大文件

转载 作者:行者123 更新时间:2023-12-02 08:02:18 25 4
gpt4 key购买 nike

我正在 Java 程序中使用 http 访问读取一个大文件。我阅读了该流,然后应用了一些标准。是否可以在读取流上应用标准,这样我就会得到一个简单的结果(我正在读取大文件)?

这是我读取文件的代码:

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
}

关于Java http-读取大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8714984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com