I have small code to read datas from "dat" type of file. It's read fine just when last line is done it's kick-off with error message
Exception in thread "main" java.lang.NullPointerException at CW2.main<CW2.java:26>

import java.io.*;
import java.util.*;

class CW2
{
	public static void main( String[] args)
	{
		try
		{
		
			BufferedReader in = new BufferedReader( new FileReader("staff2005.dat"));
			String whole;
		
			while(true)
			{
				try
				{
					whole = in.readLine();
				}
				catch (EOFException eof)
				{
					System.out.println("End of File");
					break;
				}
				
				System.out.println( whole.trim());
			}
			in.close();
		}
		catch  (IOException e) 
		{
       System.out.println ( "IO Exception =: " + e );
      }

	}
}

Just learning, please don't shot me :o . Think there is a problem with my definition of try & catch. Highligted line 26 for you.

Can you please advice on this matter??

Recommended Answers

All 6 Replies

When reading and writing binary files (which almost all files with a .dat extension are. There are thousands of different formats of course, dat is just short for data after all) don't use Readers and Writers.
Things like ByteArrayInputStream are your friends.

Another option which I use (as I need read/write access at any point in a file with a fixed record format) is RandomAccessFile.

That yields a read method like this:

public synchronized String[] readRecord(int recordId) throws
        RecordNotFoundException {
        String[] record = new String[6];

        byte[] buffer = new byte[RECORD_LENGTH];
        int flag = 0;
        int bytesread = 0;
        Logger.getLogger("suncertify.server.bs").entering(this.getClass().
            getName(), "readRecord");

        // try to move the pointer to the start of the requested record.
        // if this fails the record doesn't exist.
        try {
            datafile.seek(recordId * (RECORD_LENGTH + DELETE_FLAG_SIZE) +
                          firstRecordOffset);
        } catch (IOException ex) {
            throw new RecordNotFoundException("Record " + recordId +
                                              " does not exist");
        }
        try {
            // read the flag to check whether the record is marked deleted
            flag = datafile.readUnsignedShort();
            if (flag == DELETE_FLAG) {
                throw new RecordNotFoundException("Record " + recordId +
                                                  " has been deleted");
            }
            // read the record
            bytesread = datafile.read(buffer);
        } catch (IOException ex) {
            throw new DatabaseException("Error reading record " + recordId, ex);
        }
        StringBuilder buf = new StringBuilder(bytesread);
        for (int k = 0; k < bytesread; k++) {
            buf.append((char)buffer[k]);
        }

        record[0] = buf.substring(0, 32);
        record[1] = buf.substring(32, 96);
        record[2] = buf.substring(96, 160);
        record[3] = (new Integer(buf.substring(160, 166).trim())).toString();
        record[4] = buf.substring(166, 174);
        record[5] = (new Integer(buf.substring(174).trim())).toString();

        Logger.getLogger("suncertify.server.bs").finer(buf.toString());
        Logger.getLogger("suncertify.server.bs").exiting(this.getClass().
            getName(), "readRecord");
        return record;
    }

Thanx for your advice. I did not get it working either way, but found that effective solution with use of Vector been sugested. My mistake that I did not seen link on the bottom of the page ;) and trying to get my own solution to the problem. Always good programming exercise

Preferably use List (especially ArrayList) instead of Vector to avoid the overhead caused by all the synchronization going on in Vector.
When and if you need that, you'll know it (and know the preferred alternatives in those cases as well).

haha my teacher is oposite opinion, provided vector for reading from file. Than I used Tokenizer because I forgot there is split, but it worked fine. I learned somethig new :mrgreen: and gone be different from rest of people, so nobody can say I copied somebodies work.

Thank you for your advice. I may start hang around this forum for change of motion.

Cya around friend

Your teacher probably never worked in the real world and learned Java from a very old book and never kept that knowledge up to date.
Vector predates List by several years, it's no longer recommended for use.

For performance I once did a small test.
Programmed a servlet that did several hundred inserts into a Vector (and then read them out again).
Timed that and repeated with an ArrayList.
The version using the ArrayList (and otherwise identical) was more than 10 times faster.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.