Search code examples
javafile-handlingbluejrandomaccessfile

RandomAccessFile: Adding space after last item?


I am writing a program that allows the user to write to a text file using randomaccessfile. The user enters name, age, and address, and each of these items is 20 bytes, so the record length is 60 bytes. When the user wants to search for a record, they input a record number, the program goes to seek(n*60), and those 60 bytes are stored into a byte array, and is then outputted. This works fine except for when the user wants the last record. I can't find a way to add extra space after the name,age,address to fill in the 60 bytes. I am getting the error java.io.EOFException: null due to this.

Here is the code I use to write to the file:

      while(!done){
        junk.seek(y);
        System.out.println("Enter name.");
        junk.writeBytes(sc.nextLine());
        y+=20;
        System.out.println("Enter age.");
        junk.seek(y);
        junk.writeBytes(sc.nextLine());
        y+=20;
        System.out.println("Enter city.");
        junk.seek(y);
        junk.writeBytes(sc.nextLine());
        y+=20;
        System.out.println("Are you done?(Y/N)");
        choice = sc.nextLine();
        if(choice.equalsIgnoreCase("Y")){
            done = true;
        }

So basically how can I add extra empty space after the last item in the textfile?


Solution

  • First why do you assign 20 bytes for age?! it's kinda really big for that, does your users live for years and years!? The possible error would be for last data insertion(when user says there is no any data N) for city, because if you insert for example new york, while this doesn't get 20 bytes, so the last section will be less than 60 bytes, and vice versa, if user enters a very far far far city with friend batman while this is more than 20 bytes, it extends the data.

    so for solving, you would make sure that last data is 20 bytes as well should be.

    while(!done){
            junk.seek(y);
            System.out.println("Enter name.");
            junk.writeBytes(sc.nextLine());
            y+=20;
            System.out.println("Enter age.");
            junk.seek(y);
            junk.writeBytes(sc.nextLine());
            y+=20;
            System.out.println("Enter city.");
            junk.seek(y);
            String city=sc.nextLine();
            System.out.println("Are you done?(Y/N)");
            choice = sc.nextLine();
            if(choice.equalsIgnoreCase("Y")){
                if(city.length()>20){city-city.substring(0,20);}
                else if(city.length()<20){city=city+new String(new byte[20-city.length()]);}
                done = true;
            }
            junk.writeBytes(city);
            y+=20;
    }
    

    try this and have try. while I still think the approach you are using is really UN-logical.