JavaHTTP-读取大文件
我正在使用http访问在Java程序中读取一个大文件。我读取流,然后应用一些标准。是否有可能在读取流上应用这些条件,这样我将得到一个很轻的结果(我正在读取大文件) 以下是我读取文件的代码:JavaHTTP-读取大文件,java,file,http,Java,File,Http,我正在使用http访问在Java程序中读取一个大文件。我读取流,然后应用一些标准。是否有可能在读取流上应用这些条件,这样我将得到一个很轻的结果(我正在读取大文件) 以下是我读取文件的代码: public String getMyFileContent(URLConnection uc){ String myresult = null; try { InputStream is = uc.getInputStream(
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
}
你的标准是什么?你正在阅读的文件中有什么内容?嗯。很难理解这个问题。但我的理解是:您希望处理流而不是处理大数组。这是一件好事,但这取决于过程。如果您要应用的进程能够处理流输入,则可以。那么,请问:您希望对输入应用什么过程?旁注:将字节转换为字符时,最好明确转换(即转换)。因此,如果您使用同时接收编码(或编码名称,例如“utf-8”)的InputStreamReader构造函数,它会更好,而且不依赖于平台。