谁遇到过OutOfMemory错误?
我编写用http协议上传文件的客户端时,发现小文件可以,但上传大文件时出现OutOfMemory异常错误,下面是代码,theCGI为上传jsp的URL,thePath为文件名,当运行到循环发送数据中途引发OutOfMemory异常错误,谁知道怎么解决?
private boolean PostSingleFile(String theCGI, String thePath) {
try {
// 定义分界符
final String boundary = "---------------------------7d12ed2e2001cc";
// 合成上传前缀
String headed = "--" + boundary + "\r\n";
headed = headed + "Content-Disposition: form-data; name=\"FILE1\"; filename=\"" + thePath + "\"\r\n";
headed = headed + "Content-Type: application/octet-stream\r\n\r\n";
// 合成上传后缀
String tailed = "\r\n--" + boundary + "--\r\n";
// 建立URL对象
URL CGIurl = null;
try {
CGIurl = new URL(theCGI);
}catch(MalformedURLException e)
{
return false;
}
try {
// 建立到URL的连接
URLConnection c = CGIurl.openConnection();
// 允许输出
c.setDoOutput(true);
// 不使用缓存
c.setUseCaches(false);
// 设置content-type
c.setRequestProperty("content-type","multipart/form-data; boundary=" + boundary);
// 建立输出流
DataOutputStream out = new DataOutputStream(c.getOutputStream());
// 发送上传前缀
out.writeBytes(headed);
// 打开文件
FileInputStream fin = null;
try {
fin = new FileInputStream(thePath);
}catch(FileNotFoundException e) {
return false;
}
// 发送全部文件内容
int len;
byte[] data = new byte[2048];
while ((len=fin.read(data)) != -1) {
out.write(data, 0, len);
// 清空发送缓冲区
out.flush();
}
// 关闭文件流
fin.close();
// 发送上传后缀
out.writeBytes(tailed);
// 关闭输出流
out.close();
// 建立输入流
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String aLine;
// 已经上传标志,默认值为false
boolean uploaded = false;
// 逐行接收全部输入
while ((aLine = in.readLine()) != null) {
// 如果上传成功,置已经上传标志为true
if (aLine.indexOf("1 file uploaded.") != -1) uploaded = true;
}
// 上传失败,返回false
if (uploaded == false) return false;
}catch(IOException e) {
return false;
}
return true;
}catch(Exception e) {
return false;
}
}