javautf-8readonlyrandomaccessfile

File changes permission after writing block of byte


I am getting issue when trying to read and write to the same file using RandomAcessFile.

I am reading block of 16 bytes from a file and write them in the same file on given position (eg. 256-th).

The problem is on ra.write(b) line. When the following line is execute i got a message on the text editor Kate (I am using Linux Manjaro) saying:

The file /home/mite/IdeaProjects/IspitJuni2015/dat.txt was opened with UTF-8 encoding but contained invalid characters. It is set to read-only mode, as saving might destroy its content. Either reopen the file with the correct encoding chosen or enable the read-write mode again in the tools menu to be able to edit it.

and it turns on read-only mode. Also I tried manually to uncheck the read-only permission in Kate but it's not working either. What seems to be the problem?

 public static byte[] read(long i) throws IOException{
    File in = new File("./dat.txt");
    RandomAccessFile ra = new RandomAccessFile(in,"rw");
    byte[] readObj= new byte[16];
    if (i>in.length()/16)
    {
        return null;
    }
    ra.seek(i*16);
    ra.read(readObj);
    ra.close();
    return readObj;
}
public static void write(long i, byte[] obj) throws IOException{
    File out=new File("./dat.txt");
    RandomAccessFile ra=new RandomAccessFile(out,"rw");
    if (!out.exists())
    {
        out.createNewFile();
    }
    long size=out.length();
    if (i*16>size)
    {
        ra.seek(out.length());
        for (long j=size;j<i*16;j+=16)
        {
            byte[] b=new byte[16];
            ra.write(b);
        }
    }
    ra.seek((i)*16);
    System.out.println(new String(obj));
    ra.write(obj);
    ra.close();
}
public static void main(String[] args) throws IOException{
    write(35,read(4));
}

Solution

  • Thank you for your replies. I figured out the problem.

    Sometimes text editors are adding one extra byte at the end of the file which is not supported as byte in Java. Usually this is EOF byte and is treated as UTF-8 which Java only accepts writing/reading ASCI bytes, except manipulating through writeUTF() method.

    Also this byte is invisible in text editors and that was the reason why I write this post.

    It took me two days to find out what is the issue, but if someone gets stuck here keep in mind the EOF byte.