Reading in a text file into an array of objects using the split( ) method in Java. (There are other ways of doing this for example using useDelimiter( ) with next( ) )
Here is the text file using “#” as the delimiter. Note that there are no extra spaces or strange characters in the text file. For this to work the text file must be placed into the project (not the package) (ref: NetBeans)
Steve Eilertsen#1956#false#23.4
Andy Alpha#1987#true#45.7
Betta Bravo#1999#false#12.45
Chunky Charlie#2004#true#56.87
- We can use the method “split” to break a line into tokens based on the delimiter. In this case there are 4.
- The use of split places each token in the line into an indexed String array numbered from zero to 3.
- We use “parse” to save each token into its correct datatype.
- We create a single stand-alone object – then copy the single object into the next available index in the array.
Click here to download the Java code
What about writing to a text file? This version will write the date time to a login text file using PrintWriter.
The data and time will be appended (added to the end of the file). In case there is a problem with the file the constructor method is told to throw an IOException.
Click here to download the Java code