First the programmer must import java.io.*;
Then the file needs to be created as an object
RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");
The first argument is the filename and the second is the permission (read and write).
I keep the data file in the same directory as my class files and declare the file name in a variable at the top for flexibility e.g.
public static RandomAccessFile file;
private static String fileName = "datafile.dat";
file = new RandomAccessFile (fileName, "rw");
file.setLength(3000);
Date can be read from the file using methods and assinged to variables if needbe:
int age = file.readInt();
There are also methods for readBoolean, readDouble, and so on.
Most data is stored as a byte so the pointer will automatically move to the next item of information. Strings are an exception as they might be of different lengths. Therefore we need to set a designated size for each string and then move the pointer to a designated point.
private final static int nameLength = 30;
String name1 = file.readUTF();
file.seek(nameLength); //move the pointer on to the next name
String name2 = file.readUTF();
Task 1
Compile, execute and then study the following code:
import java.io.File;
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessFileExample {
private static void doRAF() {
try {
File file = new File("RandomAccessFileExample.dat");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// Read a character
char ch = raf.readChar();
System.out.println("Read first character of file: " + ch);
System.out.println("Read full line: " + raf.readLine());
// Seek to the end of file
raf.seek(file.length());
// Append to the end of the file
raf.write(7);
raf.writeBytes("This will complete the example");
raf.close();
} catch (IOException e) {
System.out.println("IOException:");
e.printStackTrace();
}
}
public static void main(String[] args) {
doRAF();
}
} Task 2
Write a program that asks for a password and then checks the password against what is contained in a file. The program should keep asking the user for the password until the correct one is entered.
Show your teacher the working program.
Task 3
Amend your program from Task 2 so that when the correct password is entered the user is asked to change the password and this new password is then saved over the first one in the file. Are there any issues if the new password is shorter? Show your teacher your working program.
Task 4
Using what you have learned, create a set of classes and implement them that allows for 2 or more different usernames and passwords. Users should be able to add new users which are then saved to the datafiles. Show your teacher the working program.
No comments:
Post a Comment