Search code examples
javaiobufferedinputstream

Reading x bytes at a time from a file in java


I want to read x bytes at a time from a file, (say "testFile.raw"), and output those bytes to another file.

For example:

read 20 bytes from testFile.raw -> dump into outputfile.jpg
...repeat until done...

Is this possible?


Solution

  • Here is an example using a byte array of size 20 :

        import java.io.FileInputStream;
        import java.io.FileOutputStream;
        import java.io.InputStream;
        import java.io.OutputStream;
    
        public class FileInputOutputExample {
    
            public static void main(String[] args) throws Exception {
    
                try{
                        byte[] b = new byte[20];
                        InputStream is = new FileInputStream("in.txt");
                        OutputStream os = new FileOutputStream("out.txt");
    
                        int readBytes = 0;
    
                        while ((readBytes  = is.read(b)) != -1) {
                          os.write(b, 0, readBytes);
                        }
                        is.close();
                        os.close();
    
                }catch(IOException ioe){
                    System.out.println("Error "+ioe.getMessage());
                }
             }
         }