Buffered File Reading and Writing (Java)

Just a quick dump of some code written today for buffering reading and writing of files using Java.

Note: I really don’t like the if { } else { for () { } } in the while loop, but can’t think of a better way to do this in Java at the moment – I’m hoping a night away from coding may help something spring into my brain! Please feel free to drop me a line if you have any suggestions though.

String origFilename = "inputfile";
String newFilename = "outputfile";

deleteFile(newFilename);
BufferedInputStream buffIO = null;
FileOutputStream fos = null;

try {
   byte[] bytes = new byte[1048576];

   buffIO = new BufferedInputStream(new FileInputStream(origFilename));
   fos = new FileOutputStream(newFilename);
   int b;

   System.out.println("Starting while loop");
   while ((b = buffIO.read(bytes, 0, 1048576)) != -1) {
      if (b == 1048576) {
         fos.write(bytes);
      } else {
         byte[] tempBytes = new byte[b];
         for (int i = 0; i < tempBytes.length; i++) {
            tempBytes[i] = bytes[i];
         }
         fos.write(tempBytes);
      }
   }
   System.out.println("Ended while loop");
} catch (Exception e) {
   e.printStackTrace();
   System.out.println("Exception: " + e.getMessage());
} finally {
   if (buffIO != null) {
      try {
         buffIO.close();
      } catch (Exception e) {
         System.out.println("Exception raised: " + e.getMessage());
      }
   }

   if (fos != null) {
      try {
         fos.close();
      } catch (Exception e) {
         System.out.println("Exception raised: " + e.getMessage());
      }
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s