-3

I'm trying to create a backup program to use. I can backup small files, but as soon as I try to backup any big files I get an ArrayIndexOutOfBoundsException.

        FileOutputStream fos = new FileOutputStream(dp.getPath() + ".jbackup");
    byte[] buffer = new byte[4096];
    int fileSize = (int)f.length();
    int read = 0;
    int remaining = fileSize;
    while((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
        remaining -= read;
        fos.write(buffer, 0, read);
    }

Any suggestions?

  • Is this homework? If not, you should use a library like [`IOUtils`](https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/IOUtils.html) for the task. – Mick Mnemonic Sep 23 '16 at 23:46
  • No, but I usually do everything without libs(excluding reflection, javassist) – Richard Pavlov Sep 23 '16 at 23:50
  • 1
    Well, I think that this question alone shows that maybe you shouldn't. Have a look at the various `copy()` methods in `IOUtils`; you can do this in a one-liner, and it's guaranteed to work. – Mick Mnemonic Sep 23 '16 at 23:54
  • I'm trying to use `IOUtils.copy(dis, fos);` But the files are not properly writing – Richard Pavlov Sep 23 '16 at 23:58
  • Hmm.. how are you creating the `InputStream` (`dis`)? You haven't shared that code. – Mick Mnemonic Sep 24 '16 at 00:21
  • Sorry about that. `DataInputStream dis = new DataInputStream(s.getInputStream());` `FileOutputStream fos = new FileOutputStream(dp.getPath() + ".jbackup");` The transfer just freezes. – Richard Pavlov Sep 24 '16 at 00:24
  • Okay, what does `s.getInputStream()` refer to? Note that the docs state that `Wherever possible, the methods in this class do not flush or close the stream.` so you need to close the stream(s) yourself (unlear whether that's the problem, however). – Mick Mnemonic Sep 24 '16 at 01:09

2 Answers2

0
int fileSize = (int)f.length();

The problem is here. You've just created that file. Its length is zero. It doesn't make any sense to use that as the boundary condition for this copy.

Your code appears to come from here, where fileSize comes from the sender. You should also note that in that code it's a long. Your version won't handle files over 2GB.

However it's hard to believe this is the real code. There's nothing here that would throw IndexOutOfBoundsException.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483
-1

If you want to faster way and to able copy 3GB in size files try this way :

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Foo
{
    public static void main(final String... args)
        throws IOException
    {
        Files.copy(Paths.get("/home/your file path"),
            Paths.get("/destination"), StandardCopyOption.REPLACE_EXISTING);
    }
}
Coder ACJHP
  • 1,940
  • 1
  • 20
  • 34