Search code examples
javastringjava-iorandomaccessfile

End line StringBuilder in RandomAccessFile


I'm trying use the class RandomAccessFile, but I have a problem with the Strings.

This is the first part. Write in a File:

public static void main(String[] args) throws IOException {
    File file = new File("/home/pep/java/randomFile.dat");
    RandomAccessFile fitxerAleatori = new RandomAccessFile(file, "rw");

    String[] surnames = { "SMITH", 
            "LOMU" };
    int[] dep = { 10,
            20 };
    Double[] salary = { 1200.50, 
            1200.50 };

    StringBuilder buffer = null;
    int n = surnames.length;

    for (int i = 0; i<n; i++){
        randomFile.writeInt(i+1); //ID
        buffer = new StringBuilder(surnames[i]);
        buffer.setLength(10); //10 characters
        randomFile.writeChars(buffer.toString());
        randomFile.writeInt(dep[i]);
        randomFile.writeDouble(salary[i]);
    }
    randomFile.close();
}

In the second part, I try read this file:

    File file = new File("/home/pep/java/randomFile.dat");
    RandomAccessFile randomFile = new RandomAccessFile(file, "r");

    char[] surname = new char[10];
    char aux;
    int id, dep, pos;
    Double salary;

    pos = 0;

    for (;;) {
        randomFile.seek(pos);
        id = randomFile.readInt();
        for (int i = 0; i < surname.length; i++) {
            aux = randomFile.readChar();
            surname[i] = aux;
        }
        String surnameStr = new String(surname); //HERE IS THE PROBLEM!!
        dep = randomFile.readInt();
        salary = randomFile.readDouble();
        System.out.println("ID: " + id + ", Surname: " + surnameStr + ", Departament: " + dep + ", Salary: " + salary);

        pos = pos + 36; // 4 + 20 + 4 + 8

        if (randomFile.getFilePointer() == randomFile.length())
            break;
    }
    randomFile.close();
}

Well, when I hope read:

ID: 1, Surname: SMITH, Dep: 10, Salary: 1200.50

I recived:

ID: 1, Surname: SMITH

It's like in the surname there is a end of line, because if I don't display the surname, the other info is correct.

Thank you!


Solution

  • The problem was in the char array. I change de loop for that read the chars:

    for (int i = 0; i < surname.length; i++) {
                aux = randomFile.readChar();
                surname[i] = aux != 0 ? aux : ' ';
            }