Daniel
Daniel

Reputation: 7714

recreate file from group of byte arrays

Suppose there is a file called input.zip in my folder.

I want to transfer this file from a client to a server, so what I'm currently doing is:

//client side
FileInputStream fis = new FileInputStream("input.zip");
while(fis.read(buffer) > 0) { ... }

In a nutshell: Inside the client, I separate the file in a lot of byte arrays using FileInputStream.read(buffer).

I send each of these arrays to the server and the server know the index of each of the arrays (i.e., the first array will have index 0, the second will have index 1, and so on).

Given that in the server side I have all the byte arrays and I know the order they were sent, I want to build a big byte array to store them all.

How can I build this big byte array and write the file (that should be equals to input.zip) in a file called output.zip?

Upvotes: 2

Views: 146

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109597

InputStream and OutputStream are processed sequentially.

for (;;) {
    int nread = fis.read(buffer);
    if.(nread <= 0) {
        break;
    }
    fos.write(buffer, 0, nread);
}

The last read buffer not entirely filled.

The utility class Files will do that and more.

Path path = Paths.get(“...“);
Files.copy(path, fos);

Upvotes: 1

Related Questions