I'm Working on a project.
I need to read and display a record that holds a student ID and Name . that user has entered (read by ID)
I wrote to the file using writeUTF and ArrayList ..
public void readFile(String sID) throws Exception{
studentID = sID; // take passed variable
try {
//open read file
RandomAccessFile sFile = new RandomAccessFile("newStudent.dat", "r");
//** I dont understand this long length section.
long pos = sFile.length(); // Get length of File
sFile.seek(pos); //moves pointer , I get this, but Why?
for (int i = 0; i < sFile.length(); i++) {
//read the file
String result = sFile.readUTF();
if (result.equals(studentID))
//**here I want to print whole record with the name
System.out.print(result); // testing print
}
sFile.close();
} catch (IOException e) {
System.out.print("test File caught ");
Once this is complete I will need to do a read and replace record.
I'm lost at this point , any possible suggestions. I've some similar posts and I'm not understanding what I need to fix. I just need to test this before I build out the JDesktopPane and JInternalFrame simplicity is my goal at this point.
thank you for anyfeedback or I direction
I suggest you set the file pointer to the beginning of the file, then start looping and keep checking that you didn't reach the end of the file. Here is an example of how your code can be modified:
import java.io.IOException;
import java.io.RandomAccessFile;
public class ReadUTF {
public static void main(String[] args) {
String studentID = "sID"; // take passed variable
try {
// open read file
RandomAccessFile sFile = new RandomAccessFile("c:\\temp\\newStudent.dat", "r");
sFile.seek(0); // moves pointer to the first location to read
long current = 0;
while (current < sFile.length()) {
// read the file
String result = sFile.readUTF();
if (result.equals(studentID))
// **here I want to print whole record with the name
System.out.print(result); // testing print
current = sFile.getFilePointer(); // update to the next location to be read
}
sFile.close();
} catch (IOException e) {
System.out.print("test File caught ");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.