[英]how to copy one byte array into another byte array?
我正在一個簡單的應用程序上演示P2P文件傳輸。 該應用程序獲取一個文件,然后發送數據包大小的數據塊。 接收器等待這些塊到達。 它假定將傳入的字節數組連續添加到一個較大的字節數組,一旦所有字節到達,該數組隨后將成為完整的文件。 這是假設沒有數據包丟失。 為了進行調試,我一直在嘗試傳輸一個小的txt文件。 我嘗試使用for循環,現在嘗試使用System.arraycopy,但是packetData的字節數組似乎沒有正確復制到completeFile數組。
public void run() {
try {
byte[] completeFile = new byte[fileSize];//will become the complete file when all bytes have arrived
receivingSocket = new DatagramSocket(49000);
while (bytesReceived<fileSize) {
System.out.println("@@@ Receiver waiting for packet");
byte[] buf = new byte[1500]; // Actual Ethernet packet size is 1500 bytes
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
receivingSocket.receive(packet);
byte[] packetData = Arrays.copyOf(packet.getData(), packet.getLength());
deliverData(packetData);
if(headerReceived && packetsReceived>1)
{
//add incoming bytes to the completeFile
System.arraycopy(packetData, 0, completeFile, bytesReceived, packetData.length);
bytesReceived = bytesReceived + packetData.length;
}
}
FileOutputStream fops = new FileOutputStream("D:\\Desktop\\testing2"+fileExtension);
System.out.println("@@@ BUILDING FILE");
fops.write(completeFile);
fops.close();
} catch (Exception e) {
System.out.println("@@@ SOMETHING WENT WRONG!!!!!!!!!!!!!!");
stopListening();
}
}
您無需復制任何內容。 您可以在循環中每次都從用於構造DatagramPacket,
的字節數組直接寫入文件,並且可以將該字節數組以及數據包的長度直接傳遞給其他方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.