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.

Main.java 


/**
* Author : Berk Soysal
*/

package herrberk;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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 = in.read()) != -1) { // stop when in.read() returns -1 (End Of File)
     out.write(b); // write one byte at a time to a new file
    }
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   } 
  
  }
}


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

Author:

Software Developer, Codemio Admin

Disqus Comments Loading..