Java File IO Compendium

Posted by Warren Taylor on Stack Overflow See other posts from Stack Overflow or by Warren Taylor
Published on 2008-08-13T14:51:00Z Indexed on 2010/04/30 2:27 UTC
Read the original article Hit count: 401

Filed under:
|

I've worked in and around Java for nigh on a decade, but have managed to ever avoid doing serious work with files. Mostly I've written database driven applications, but occasionally, even those require some file io. Since I do it so rarely, I end up googling around for quite some time to figure out the exact incantation that Java requires to read a file into a byte[], char[], String or whatever I need at the time.

For a 'once and for all' list, I'd like to see all of the usual ways to get data from a file into Java, or vice versa. There will be a fair bit of overlap, but the point is to define all of the subtle different variants that are out there.

For example:

  1. Read/Write a text file from/to a single String.
  2. Read a text file line by line.
  3. Read/Write a binary file from/to a single byte[].
  4. Read a binary file into a byte[] of size x, one chunk at a time.

The goal is to show concise ways to do each of these. Samples do not need to handle missing files or other errors, as that is generally domain specific. Feel free to suggest more IO tasks that are somewhat common and I have neglected to mention.

© Stack Overflow or respective owner

Related posts about java

Related posts about file-io