Java Reference
In-Depth Information
// Increment the file read counter by 1
incrementReadCounter(raf);
raf.close();
}
public static void incrementReadCounter(RandomAccessFile raf) throws IOException {
// Read the current file pointer position so that we can restore it at the end
long currentPosition = raf.getFilePointer();
// Set the file pointer in the beginning
raf.seek(0);
// Read the counter and increment it by 1
int counter = raf.readInt();
counter++;
// Set the file pointer to zero again to overwrite the value of the counter
raf.seek(0);
raf.writeInt(counter);
// Restore the file pointer
raf.seek(currentPosition);
}
public static void initialWrite(String fileName) throws IOException{
// Open the file in read-write mode
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
// Write the file read counter as zero
raf.writeInt(0);
// Write a message
raf.writeUTF("Hello world!");
raf.close();
}
}
File Read Counter: 0
File Text: Hello world!
----------------------------
File Read Counter: 1
File Text: Hello world!
----------------------------
Search WWH ::




Custom Search