I was wondering what are the various options available for opening and reading from files in Java. I'm trying to open a file and parse through it grabbing each line which consists of : value 1 <delimiter> value 2 <delimiter> value 3.....
I wanted to assign each value into a separate array or other such object. Each of these values will represent an entity(ies) that will be used when I use JFreeChart to create some graphs. Thanks in advance for any help/advice.
If you have a text file with a predictable sequence of contents, you can use a java.util.Scanner. I suspect it incorporates BufferedReaders, but can be used as a single object. It only works on simple, predictable, text files as far as I know, however.
File contents = new File(path); FileInputStream contentStr = new FileInputStream(contents); BufferedInputStream contentBuff = new BufferedInputStream(contentStr); DataInputStream contentData = new DataInputStream(contentBuff);
Whats the easiest way to break up each line read in into separate components (i.e. tilde delimited list of values) and best/easiest way to store the values for reference later on (loop through each value and store in a dataset for use in a JFreeChart)? Thanks again.
[Stan James]: Campbell's suggestion for Scanner is a bit more advanced
A Scanner has more advanced options (and more methods total) than a BufferedReader. But using it can actually be simpler. For one thing, you usually don't need to combine it with other readers like FileReader. The equivalent of Gabriel's code would be:
Digression: the only thing I don't like is that Scanner conceals exceptions if you don't think to check when you're done:
Of course, PrintWriter has the same problem (worse since PrintWriter doesn't let you discover what the error was), and it almost never actually matters in practice. Seems like 99.9% of the errors you might encounter are thrown by the constructor, not the later read/write methods. So Scanner and PrintWriter work well for most all practical purposes. [ May 01, 2007: Message edited by: Jim Yingst ]
Good point on Scanner. I was imagining using regex to specify delimiters, but our intrepid original poster can get a lot of mileage out of it without regex.
I will stick with one bit of earlier advice - we've given two suggestions, try em both. Make a place to save short snippets of code for common things because you will want them again one day. And have fun.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi