Results 1 to 14 of 14
Like Tree1Likes
  • 1 Post By Norm

Thread: Busy week - Using RandomAccessFile

  1. #1
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    104
    Rep Power
    0

    Default Busy week - Using RandomAccessFile

    I'm writing student ID number and their gpa to a .dat file using (as per the school assignment) RandomAccessFile. I decided to create a Student class that has arguments (int studentID , float gpa).
    I setup a for loop to let the user enter the student ID's and gpa for the studentArray []. When I try to write the studentArray[] to the .dat file, I get an error:

    The method write(int) in the type RandomAccessFile is not applicable for the arguments (Student)

    I tried using writeFloat, writeInt but it doesn't work either. Do I need to setup a separate array for studentID and gpa...then write the array to the .dat file according to the file type?

    After that, I need to prompt the user to enter a student ID and return that students GPA. I assume that is why we were assigned to use RandomAccessFile.

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    
    public class ReadWrite {
        public static void main(String[] args) throws IOException{
            Scanner input = new Scanner(System.in);
            RandomAccessFile inout = new RandomAccessFile("Stu.dat", "rw");
            
            System.out.print("Class size: ");
            int size = input.nextInt();
            
            int[] studentID = new int[size];
            float[] studentGPA = new float[size];
            
            for(int i = 0 ; i < studentID.length; i++){
                System.out.print("Enter student: ");
                studentID[i] = input.nextInt();
                System.out.print("Enter GPA: ");
                studentGPA[i] = input.nextFloat();             
            }
            
            for(int i = 0 ; i < studentID.length ; i++){
                inout.writeInt(studentID[i]);
                inout.writeFloat(studentGPA[i]);
            }
            inout.close();
            
            try{
                System.out.println("\n-----Find Student GPA------");
                System.out.println("----------------------------");
                System.out.print("Enter student ID: ");
                int studID = input.nextInt();
                
                while(){
                    if(inout.readLong() == studID){
                        System.out.println("Student ID: ");
                        
                    }
                }
            }catch(FileNotFoundException ex){
                ex.printStackTrace();
            }
        }
    }
    Still a lot of holes but this is the direction I'm headed..
    Last edited by javaStooge; 05-03-2014 at 11:23 PM. Reason: Revised Code

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Busy week - Using RandomAccessFile

    The method write(int) in the type RandomAccessFile is not applicable for the arguments (Student)
    When you try to use classes and methods, you need to read the API doc for those methods. Java is strict with types.
    A Student object is NOT an int.

    How do you want the bytes for the data to be written to the file?
    What goes in the first n bytes
    and the next m bytes
    etc
    n and m are determined by the type of data. Some take 2, some 4, some 8, some have their length as a header
    Last edited by Norm; 05-03-2014 at 10:36 PM.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    104
    Rep Power
    0

    Default Re: Busy week - Using RandomAccessFile

    1. I don't understand your response... I see in the text where they talk about UNICODE (16 bit) and ASCII (8 bit) but I don't see any examples where you declare how you want your data to be written. Is it necessary for writing data, or reading?

    2. I see that you don't close the file until you are completely finished..at the end of the code. Isn't that detrimental to the security of the data on the file?

    3. How would you scan the .dat file for a long int (studentID) and return the GPA if its all stored in binary form??
    Last edited by javaStooge; 05-03-2014 at 11:39 PM.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Busy week - Using RandomAccessFile

    how you want your data to be written
    That is determined by the method you use.

    The data is written to the file in bytes. Say an int uses 4 bytes, a double could use 8, a long 8.
    Given that each type of data has a length, you can specify the byte where a variables data is stored.
    If I use letters for the type of data in the file. If the types that are written are int, float and long the files contents could be shown like this: IIIIDDDDDDDDLLLLLLLL
    To read the long, seek to byte 12, the readLong() method will read the next 8 bytes into a long variable. See the API doc for the number of bytes used.

    The flush() method will write the contents of the buffer to disk.

    How would you scan the .dat file for a long
    You don't scan a random access file. You MUST know the format of the file to find the beginning byte of the data you want to read.
    Last edited by Norm; 05-04-2014 at 12:41 AM.
    javaStooge likes this.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    104
    Rep Power
    0

    Default Re: Busy week - Using RandomAccessFile

    Thanks Norm, that actually made a lot more sense for me! I see what you meant by how I want the bytes written to the file. I will take another look at it and see what I can do to adjust.

    I should set limits on the studentID and GPA, so the program knows what to look for when it reads the .dat file.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Busy week - Using RandomAccessFile

    It would help if you had a hex editor so you can see the bytes in the file.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    104
    Rep Power
    0

    Default Re: Busy week - Using RandomAccessFile

    Well, I think I've figured it out...because I'm not getting any errors, but I'm also not getting any result in the console. When I enter the student ID to retrieve the gpa...nothing kicks back from the .dat file. When I looked at the size of the file its 24 bytes.

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    
    public class ReadWrite {
    
    	public static void main(String[] args) throws IOException {
    		
    		Scanner input = new Scanner(System.in);
    		try{
    			RandomAccessFile inout = new RandomAccessFile("Stu.dat", "rw");
    			
    			//Define class size and students
    			System.out.print("Class size: ");
    			int size = input.nextInt();
    			
    			//Student[] student = new Student[size];
    			int[] studentID = new int[size];
    			double [] studentGPA = new double[size];
    			
    			for(int i = 0; i < studentID.length; i++){
    				System.out.print("Enter student: ");
    				studentID[i] = input.nextInt();
    				if(studentID[i] > 9999){
    					System.out.println("Student ID is 4 digts long");
    					System.out.print("Enter student: ");
    					studentID[i] = input.nextInt();
    				}
    				System.out.print("Enter GPA: ");
    				studentGPA[i] = input.nextDouble();
    				if(studentGPA[i] > 4.00){
    					System.out.println("GPA cannot be greater than 4.0");
    					System.out.print("Enter GPA: ");
    					studentGPA[i] = input.nextDouble();
    				}
    			}	
    			
    			// Print contents to file
    			for(int i = 0 ; i < studentID.length;i++ ){
    				inout.writeInt(studentID[i]);
    				inout.writeDouble(studentGPA[i]);
    			}
    			
    				
    				System.out.println("\n------Find Student GPA------");
    				System.out.println("----------------------------");
    				System.out.print("    Enter Student ID: ");
    				int studID = input.nextInt();
    				
    				while(inout.read() != -1){
    					if(inout.readInt() == studID){
    						System.out.println("Student ID: " + inout.readInt());
    						System.out.println("GPA: " + inout.readDouble());	
    					}
    					else{
    						System.out.println("Student Not Found");
    					}
    				}	
    			
    		}catch(FileNotFoundException ex){
    			ex.printStackTrace();
    		}
    	}
    }
    Last edited by javaStooge; 05-04-2014 at 02:01 AM.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Busy week - Using RandomAccessFile

    Add some println statements that print out the values of all the variables that are assigned values so you can see what the computer sees when the code is executed.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    104
    Rep Power
    0

    Default Re: Busy week - Using RandomAccessFile

    Quote Originally Posted by Norm View Post
    Add some println statements that print out the values of all the variables that are assigned values so you can see what the computer sees when the code is executed.
    Add println's right before the content is printed to file.

    Class size: 2
    Enter student: 3123
    Enter GPA: 3.2
    Enter student: 2121
    Enter GPA: 2.34
    Student:3123
    GPA:3.2
    Student:2121
    GPA:2.34

    ------Find Student GPA------
    ----------------------------
    Enter Student ID: 2121

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Busy week - Using RandomAccessFile

    Where is the output from the println statements for the code in the search loop?
    ALL the read statements need to read into a variable and the contents of that variable printed for debugging. Too many read statements do NOT save the value in a variable.

    You need to read the API doc for the class and look specifically at the discussion of the "file pointer".
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    104
    Rep Power
    0

    Default Re: Busy week - Using RandomAccessFile

    I tested the program using the getFilePointer and length() of the file to get a better idea of what is going on. I realize I need to reset the pointer, by seek(0), and then read the contents of the file. The way I visualize the file is studentID (s) and gpa (g) : ssssggggggggssssgggggggg
    Then I use the read loop starting at 0 to read (8 bits) that match stuID and then read the following double.

    None of this is discussed in our textbook...they one example that writes the exact values into the file and reads it right back.

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Busy week - Using RandomAccessFile

    Did you change all the read statements to read into a variable that could be printed for debugging?

    read (8 bits) that match stuID
    8 bits is one byte. An int takes 4 bytes.
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    104
    Rep Power
    0

    Default Re: Busy week - Using RandomAccessFile

    Output:
    XML Code:
    Class size: 1
    Enter student: 1234
    Enter GPA: 2.34
    length of file:36
    file pointer:36
    
    ------Find Student GPA------
    ----------------------------
        Enter Student ID: 1234
    Student: 1234    GPA: 1.4874687046941417E-295
    Is the printed result because I'm not adding up the bytes correctly?
    Is this any closer to the truth..
    Code:
    Java Code:
    try {
    				inout = new RandomAccessFile(new File("Stu.dat"), "rw");
    				long fileSize = inout.length();
    				final int total = 36;
    				long totalStudents = fileSize/total;
    				inout.seek(0);
    				System.out.println("\n------Find Student GPA------");
    				System.out.println("----------------------------");
    				System.out.print("    Enter Student ID: ");
    				int studID = input.nextInt();
    				for(int j = 0 ; j < totalStudents ; j++){
    					studID = inout.readInt();
    					for(int i = 0 ; i < studentID.length; i++){
    						inout.readByte();
    				}	double studGPA = inout.readDouble();
    					for(int i = 0; i < studentGPA.length; i++){
    						inout.readByte();
    					}
    					System.out.println("Student: " + studID + "    GPA: " + studGPA);
    				}
    Last edited by javaStooge; 05-04-2014 at 04:35 AM.

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default Re: Busy week - Using RandomAccessFile

    I'm not adding up the bytes correctly
    The bytes should be read the same way they were written. If written with a writeFloat() they should be read with a readFloat()
    What is this statement for? inout.readByte();
    It reads a byte but doesn't save it. It will move the file pointer so the readDouble() is not aligned to read the bytes for a double.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. RandomAccessFile Problem
    By threlot in forum New To Java
    Replies: 2
    Last Post: 11-12-2013, 05:27 AM
  2. Connection is busy with results for another hstmt
    By amritpalpathak in forum New To Java
    Replies: 8
    Last Post: 07-17-2010, 11:46 AM
  3. RandomAccessFile
    By swati.jyoti in forum New To Java
    Replies: 1
    Last Post: 04-22-2009, 04:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •