1

In my method, I'm saving data from file to an output stream.

For now, it looks like this

public void readFileToOutputStream(Path path, OutputStream os) {
    byte[] barr = Files.readAllBytes(path)

    os.write(barr);
    os.flush();
}

But in this solution, all bytes are loaded into memory, and I want to use buffer to release some of it.

What can I use to supply my reading with buffer?

VanDavv
  • 836
  • 2
  • 13
  • 38
  • Take a look at this answer in the linked question:http://stackoverflow.com/a/19194580/1743880 There is a built-in for that: `Files.copy(Path, OutputStream)`. – Tunaki May 24 '16 at 17:00

4 Answers4

1
  1. easist way is to use Commons IO library

    public void readFileToOutputStream(Path path, OutputStream os) throws IOException {
      try(InputStream in = new FileInputStream(path.toFile())){
        IOUtils.copy(in, os);
      }
    }
    
  2. You can implement on your own similar to IOUtils.copy

    public void readFileToOutputStream(Path path, OutputStream os) throws IOException {
      try (InputStream fis = new FileInputStream(path.toFile());
           InputStream bis = new BufferedInputStream(fis)) {
        byte[] buffer = new byte[4096];
        int n;
        while ((n = bis.read(buffer)) >= 0) {
          os.write(buffer, 0, n);
        }
      }
    }
    
waltersu
  • 1,191
  • 8
  • 20
0

If i understand your question right, you would like to only write a specified amount of bytes to memory?

outputstreams write method can also write a specified byte array from a starting offset and length.

https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html

public void readFileToOutputStream(Path path, OutputStream os, int off, int len) {
    byte[] barr = Files.readAllBytes(path)

    os.write(barr, off, len);
    os.flush();
}
Henry
  • 29
  • 5
0

Use buffered streams to manage the buffer for you:

public void readFileToOutputStream(Path path, OutputStream os) {
    try (FileInputStream fis = new FileInputStream(path.toFile())) {
        try (BufferedInputStream bis = new BufferedInputStream(fis)) {
            try (DataInputStream dis = new DataInputStream(bis)) {
                try (BufferedOutputStream bos = new BufferedOutputStream(os)) {
                    try (DataOutputStream dos = new DataOutputStream(bos)) {
                        try {
                            while (true) {
                                dos.writeByte(dis.readByte());
                            }
                        } catch (EOFException e) {
                            // normal behaviour
                        }
                    }
                }
            }
        }
    }
}
Lee
  • 738
  • 3
  • 13
0

Use FileInputStream::read(byte[] b, int off, int len) link to read up to len bytes to buffer b and FileOutputStream::write(byte[] b, int off, int len) link2 to write from buffer

Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27