Useful Java Code Snippets 9 - Reading & Writing Byte Streams of an Image

Hello everyone, today we are going to work on reading and writing byte streams of an image file, which is one of the lowest level approaches to working with the file system. 

Let me start with introducing two primary classes that we need to successfully implement our program. The first one is called FileInputStream and the other one is FileOutputStream. We are going to use them to read and write an image file. Let's place our image file in our working directory and start writing our program.

Now let us create instances of FileInputStream and FileOutputStream classes first. Then we will need an integer file to store each byte that we read from the file temporarily and write it out to a file one byte at a time. 

* Author : Berk Soysal

package herrberk;


public class Main {

  public static void main(String[] args) {

   try (
    FileInputStream in = new FileInputStream("image.jpg"); // For reading byte streams
    FileOutputStream out = new FileOutputStream("newimage.jpg"); //For writing byte streams
     ) {
    int b; //used to store one byte at a time temporarily
    while ((b = != -1) { // stop when returns -1 (End Of File)
     out.write(b); // write one byte at a time to a new file
   } catch (FileNotFoundException e) {
   } catch (IOException e) {

After running the program, our directory shows the created newImage.jpg as shown in the figure below;


Please leave a comment if you have any questions or comments. Thanks!

Continue Reading Useful Java Code Snippets 10 - Bubble Sort in Java


Software Developer, Codemio Admin

Disqus Comments Loading..