谁遇到过OutOfMemory错误?

artgolf 2001-09-20 04:47:44
我编写用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;
}
}
...全文
157 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunni 2001-09-22
  • 打赏
  • 举报
回复
i have too, i used the static , oh,so poor ,but i don't believe gc
lhj_fmx 2001-09-22
  • 打赏
  • 举报
回复
java -Xmx256 theapplication.jar 不能解决本质问题,时间长了也是会出现同样问题的,我建议大家还是对代码优化一下。可用内存分配跟踪软件,来擦看各中对象的分配情况。
lhj_fmx 2001-09-22
  • 打赏
  • 举报
回复
我也遇到此类问题,我对代码又重新优化了一边,我是在做application时遇到的,优化后,程序运行有了明显的改善。如有兴趣可于我联系,我在杭州,zgd_lhj@21cn.com
kare 2001-09-22
  • 打赏
  • 举报
回复
请大家畅所欲言
artgolf 2001-09-21
  • 打赏
  • 举报
回复
错了,也许是java -Xmx256m theapplication.class
artgolf 2001-09-21
  • 打赏
  • 举报
回复
设置堆栈大小我倒是知道,如设置最多用256M内存来运行:
java -Xmx256 theapplication.class
kare 2001-09-21
  • 打赏
  • 举报
回复
我的错误提示:
Exception occurred during event dispatching:

java.lang.OutOfMemoryError

<<no stack trace available>>
程序里没有死循环或死递归调用,因为不是每次运行都会出这个错误,大部分都是正常的
我用的是JB5,编写的是普通的应用程序
请问在那里可以设置程序的调用堆栈大小,或有什么有效的解决办法
kare 2001-09-21
  • 打赏
  • 举报
回复
我也碰到这个问题
但我是作Appliction,该Appliction中有n多个递归调用,急阿……

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧