我有一个我打算通过网络发送的文件,所以我尝试将其拆分为字节数组:
File myFile = new File(selectedImagePath);
byte[] fileByteArray = new byte[(int) myFile.length()];
Log.i("MyApp", " File byte size: " + fileByteArray.length);
List<byte[]> listOfBytes = new ArrayList<byte[]>();
int pos = 0;
while (pos < fileByteArray.length)
{
int length = pos + size > fileByteArray.length ? fileByteArray.length - pos : size;
byte[] act_byte = new byte[length];
Log.i("MyApp","Length: "+length);
System.arraycopy(fileByteArray, pos, act_byte, 0, length);
pos += length;
listOfBytes.add(act_byte);
}
List<byte[]> sending=new ArrayList<byte[]>();
for(byte[] ba:listOfBytes)
{
byte[] arr = new byte[ba.length + 2];
arr[0] = new Integer(W).byteValue();
arr[1] = new Integer(Z).byteValue();
System.arraycopy(ba, 0, arr, 2, ba.length);
sending.add(arr);
}
让文件大小为10000字节。
在接收大小上,我得到10000字节,但文件不可读。
byte[] message = new byte[size + 2];
DatagramPacket p = new DatagramPacket(message, message.length);
s = new DatagramSocket(SERVERPORT);
List<byte[]> incomingBA=new ArrayList<byte[]>();
while (true)
{
s.receive(p);
int a=new Byte(p.getData()[0]).intValue();
int b=new Byte(p.getData()[1]).intValue();
int actualSize = p.getLength();
byte[] actualBA=new byte[actualSize-2];
System.arraycopy(p.getData(),2,actualBA,0,actualBA.length);
incomingBA.add(actualBA);
if(X==22)
{
byte[] result=concatenateByteArrays(incomingBA);
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/Download/X.jpg");
//BufferedOutputStream bos = new BufferedOutputStream(fos);
fos.write(result,0,result.length);
fos.flush();
fos.close();
incomingBA.clear();
}
public byte[] concatenateByteArrays(List<byte[]> blocks) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (byte[] b : blocks) {
os.write(b, 0, b.length);
}
return os.toByteArray();
}
我做错了什么?
答案 0 :(得分:0)
我忘了把文件的内容读入字节数组,所以我需要使用这段代码:
FileInputStream fileInputStream = new FileInputStream(myFile);
fileInputStream.read(fileByteArray);
fileInputStream.close();