我正在处理服务器到客户端文件传输的示例。当我尝试传输大文件时(例如,我有一个500MB的视频文件),它会显示错误Android:java.lang.OutOfMemoryError,无法分配360318346字节的内存空间,只有5802592自由字节和87MB直到OOM。请帮助我解决这个错误。
服务器端的一些代码:
服务器端的一些代码:
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket){
this.socket= socket;
}
@Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory(),"RAHASYA.mp4");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
// socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,sentMsg,Toast.LENGTH_LONG).show();
}});
客户端的一些代码
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
@Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
out.println("Sockt "+socket.getInetAddress());
File file = new File(Environment.getExternalStorageDirectory(),"RAHASYA.mp4");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
while (true) {
int bytesRead = is.read(bytes);
if (bytesRead < 0) break;
bos.write(bytes, 0, bytesRead);
// Now it loops around to read some more.
}
bos.close();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"Finished",Toast.LENGTH_LONG).show();
}});