在J2ME中使用多个hppt连接上传大文件
问题描述:
我想从诺基亚手机上传一个大文件到服务器,我使用下面的代码。此代码适用于小文件。当我想上传更大的文件(大约10mb)时,我收到内存不足的消息。有谁知道我怎样才能转换这个代码上传文件使用 多个httpConnections,每个连接发送一个文件块。我们假设服务器支持这一点。在J2ME中使用多个hppt连接上传大文件
fc = (FileConnection)Connector.open("file:///myfile", Connector.READ);
is = fc.openInputStream();
// opening http connection and outputstream
HttpConnection http = (HttpConnection)Connector.open(url, Connector.WRITE);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", type);
http.setRequestProperty("Connection", "close");
OutputStream os = http.openOutputStream();
int total = 0;
while (total < fileSize) {
byte b[] = new byte[1024];
int length = is.read(b, 0, 1024);
os.write(b, 0, length);
total += length;
}
os.flush();
int rc = http.getResponseCode();
os.close();
http.close();
答
尝试移动while
循环内的os.flush()
呼叫,所以缓冲器每次冲洗。目前,您的整个文件在通过线路发送之前正在被读入内存。
如果这样不能解决问题,我会建议使用profiler在模拟器中运行代码,以便更好地了解内存在哪里被用完。
答
尝试在while循环之前移动缓冲区初始化byte b[] = new byte[1024];
- 您无需每次都重新创建它。并尝试将System.gc()
放入循环中 - 它可能有帮助(或不可)。
此外,某些设备可能会尝试把整个文件到内存中,当你调用fc.openInputStream
os.flush不while循环里面工作。我会尝试使用分析器。我正在寻找像这样的解决方案:http://discussion.forum.nokia.com/forum/showthread.php?t=176546&highlight=upload+chunk(请参阅最新评论) – user75569 2009-12-11 08:06:01