Reading and Writing Student Info With a File

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 14082 Views - Last Post: 05 December 2011 - 09:57 AM Rate Topic: -----

#1 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Reading and Writing Student Info With a File

Posted 04 December 2011 - 05:57 PM

This is the first time I've had to write a program with a file. I just have a quick question about what is meant in the last part of the assignment. First we were told to write a Student class to create a Student object with name, DOB, student ID, etc.; I already completed that. Now I'm told to "Create a test class. It will read in students' info from a file. The first line of the file contains a number indicating how many students information are specified in the file. And the rest in the file contains information of each individual student. The test class will receive the name of the file through command line argument, create an array to store students info, read in the information from the file, and print out these students' info via calling the toString method. You need to submit a zip file containing the two class files and also student info file."

Previously, we've only created object classes and then a "test" class which reads the user input and creates an object by calling the object class. (like this: Room Occupancy Class) I'm getting thrown off by the whole file concept; how is this different than before? And the last line is confusing me as well. Does this mean I'll have 3 seperate classes to submit? :helpsmilie:
Thanks so much!

Is This A Good Question/Topic? 0
  • +

Replies To: Reading and Writing Student Info With a File

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10437
  • View blog
  • Posts: 38,651
  • Joined: 27-December 08

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 06:16 PM

Traditionally, you have read in the Student information from the console using Scanner instead of from a File. You can point your Scanner to an external text File instead of System.in. You can also use other File I/O tools as illustrated in this tutorial.

You will only be submitting to Java class files, and then the text file with the Student information.
Was This Post Helpful? 1
  • +
  • -

#3 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 07:41 PM

Ohhh ok. So I'll jest be creating a text file on something such as "notepad". And then reading the data from the text file rather than from the user via some java class and using the Student class to create the objects correct?
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 08:05 PM

View Postkikib92, on 04 December 2011 - 10:41 PM, said:

Ohhh ok. So I'll jest be creating a text file on something such as "notepad". And then reading the data from the text file rather than from the user via some java class and using the Student class to create the objects correct?

Your choice ....

If you create your Student objects using a Java program you can save them as Student objects into a file and read them from there
If you want to define your Student using a regular editor (or an other application) you can write them as ascii data in a text file
Was This Post Helpful? 1
  • +
  • -

#5 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 09:35 PM

View Postpbl, on 04 December 2011 - 08:05 PM, said:

View Postkikib92, on 04 December 2011 - 10:41 PM, said:

Ohhh ok. So I'll jest be creating a text file on something such as "notepad". And then reading the data from the text file rather than from the user via some java class and using the Student class to create the objects correct?

If you create your Student objects using a Java program you can save them as Student objects into a file and read them from there


How do I go about doing it that way?
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 09:43 PM

First you have your Student class to implements Serializable
(no method to implement) then these are quite clear

http://docs.oracle.c...nputStream.html
http://docs.oracle.c...tputStream.html



*edited: oups put the right pointers]

This post has been edited by pbl: 04 December 2011 - 10:22 PM

Was This Post Helpful? 1
  • +
  • -

#7 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 09:54 PM

The class I'm in is still pretty elementary; only the beginning of my java series in college. We wont be covering FileInputStream/FileOutputStream until next semester I believe. Currently, the chapter we are in is called "Strings and Text I/O" and mentions reading data using scanner and writing data using PrintWriter. I know how I would create objects using the scanner but how would I save it to a file? Would it be something like:
java.io.File file = new java.io.File("students.txt");
Scanner input = new Scanner(file);

while (input.hasNext()) {
  //read data from scanner to create objects
}
input.close();



Or are you supposed to use PrintWriter to write objects to a file?

This post has been edited by kikib92: 04 December 2011 - 09:56 PM

Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 10:25 PM

FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(student);

Oups !!! my previous post didn;t have the right pointers.. I have updated it
Was This Post Helpful? 0
  • +
  • -

#9 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 10:51 PM

I stumbled across that method of writing files while trying to find a solution to my problem, but is there an even more basic way? I'm not technically allowed to use ObjectOutputStream because we haven't covered binary I/O yet, only text. I don't understand why not if we are supposed to be writing files. Is it possible to write objects to a file using printWriter?

This post has been edited by kikib92: 04 December 2011 - 10:52 PM

Was This Post Helpful? 0
  • +
  • -

#10 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 11:29 PM

View Postmacosxnerd101, on 04 December 2011 - 06:16 PM, said:

Traditionally, you have read in the Student information from the console using Scanner instead of from a File. You can point your Scanner to an external text File instead of System.in.
You will only be submitting to Java class files, and then the text file with the Student information.

Does this mean the Student info will be hardcoded?? Nothing will be created by the user?
Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 11:43 PM

If you wait for your teacher to show you all the classes of the API you will be im school for another 10 years :)
The API is there for you to browse into it. Any teacher should be proud of students doing so... actually a teacher job should be to teach you how to browse in the API rather than teaching you all different classes
Was This Post Helpful? 1
  • +
  • -

#12 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 11:49 PM

Going by the only two examples given in the book, this is what I came up with. I've tested my Student class and I know it works. The read and write files compiles but they don't run. I get "Exception in thread "main" java.io.FileNotFoundException: students.txt (No such file or directory)"
Could someone please guide me in the right direction and help me understand what I'm doing? :blink:
public class Student {
	private String fName;
	private String mName;
	private String lName;
	private String UFID;
	private String DOB;
	private String month, day, year;
	
	//Default Constructor
	public Student() {
		fName = "Anonymous";
		mName = "";
		lName = "Anonymous";
		UFID = "xxxx-xxxx";
		DOB = "MM/DD/YYYY";
	}
	
	//Set Name
	public void setNames(String name) {
		String[] nameSplit = name.split(" ");
		fName = nameSplit[0];
		lName = nameSplit[nameSplit.length - 1];
		if (nameSplit[1] != lName) {
			mName = nameSplit[1];
		}
	}
	
	//Set UFID 
	public void setUFID(String id) {
		//Check that characters are integers (8 total)
		int numbers = 0;
		for(int i=0; i<4; i++) {
			if (Character.isDigit(id.charAt(i)))
				numbers++;
		}
		for(int i=5; i<9; i++) {
			if (Character.isDigit(id.charAt(i)))
				numbers++;
		}
		//Check that 9 char long, - in middle, and contains all numbers
		char hyphen = id.charAt(4);
		if (id.length() == 9 && hyphen == '-' && numbers == 8) {
			UFID = id;
			System.out.println("Valid");
		}
		else {
			System.out.println("UFID is not valid. ");
		}
	}
	
	//Set DOB
	public void setDOB(String dob) {
		//Check for valid date format
		char[] dobChars = dob.toCharArray();
		if (((dobChars[1] == '/') && (dobChars[3] == '/' || dobChars[4] == '/')) ||
			((dobChars[2] == '/') && (dobChars[4] == '/' || dobChars[5] == '/'))) {
			//Check for valid date
			String[] dobSplit = dob.split("/");
			month = dobSplit[0];
			day = dobSplit[1];
			year = dobSplit[2];
			
			if (validate(month, day, year)) {
				System.out.println("Valid date of birth.");
				DOB = dob;
			}
			else {
				System.out.println("Invalid date of birth.");
			}
		}
		else {
			System.out.println("Invalid date format.");
		}
	}
			
			
	//Check if date is valid	
	public static boolean validate(String month, String day, String year) {
		//convert year to #
		int year_ = Integer.parseInt(year);
		//valid day of month
		if (day.equals("31") && 
		  (month.equals("4") || month.equals("6") || month.equals("9") ||
           month.equals("11") || month.equals("04") || month.equals("06") ||
           month.equals("09"))) {
			return false; // only 1,3,5,7,8,10,12 has 31 days
	     } 
	     
	    //leap year
	    else if (month.equals("2") || month.equals("02")) {
        	if((year_ % 4==0 && year_ % 100!=0) || (year_ % 400==0)){
				if(day.equals("30") || day.equals("31")){
				  return false;
			  	}
			  	else{
				  return true;
			  	}
			}
			else {
				if(day.equals("29")||day.equals("30")||day.equals("31")){
					return false;
		    	}
		    	else{
				  return true;
		    	}
		    }
		 }
	    else{				 
			return true;				 
	    }
	}
	
	//Get methods
	public String getFullName() {
		String fullName;
		if (mName.matches("")) {
			fullName = fName + " " + lName;
		}
		else {
			fullName = fName + " " + mName +  " " + lName;
		}
		return fullName;
	}
	
	public String getDOB() {
		return DOB;
	}
	
	public String getUFID() {
		return UFID;
	}
	
	//toString method
	public String toString() {
		return "Name: " + lName + ", " + fName + "\nUFID: " + UFID + "\nD.O.B.: " + DOB;
	}
}


^^I don't understand the purpose of the get methods, but I was told to add them... :/

import java.util.Scanner;

public class ReadStudentData {
	public static void main(String[] args) throws Exception {
		//Create file instance
		java.io.File file = new java.io.File("students.txt");
		
		// Create a Scanner for the file
    	Scanner input = new Scanner(file);

		//Create object array
		Student[] students = new Student[2];
		
    	// Read data from a file
    	for(int i=0; i<2; i++) {
      		String name = input.nextLine();
      		students[i].setNames(name);
      		
      		String ufid = input.next();
      		students[i].setUFID(ufid);
      		
      		String dob = input.next();
      		students[i].setDOB(dob);
      		
      		System.out.println(students[i].toString());
    	}

    	// Close the file
    	input.close();
  	}
}



public class WriteStudentData {
	public static void main(String[] args) throws Exception{
		//Create a file object called students.txt
		java.io.File file = new java.io.File("students.txt");
   		
   		if (file.exists()) {
      		System.out.println("File already exists");
      		System.exit(0);
    	}

    	// Create file
    	java.io.PrintWriter output = new java.io.PrintWriter(file);

    	// Write formatted output to the file
    	output.println("Nicolas Molinet");
    	output.println("1234-5678");
    	output.println("12/10/1990");
    	output.println("Kirstie Dawn Booras");
    	output.println("2232-5544");
    	output.println("3/15/1992");
    	

    	// Close the file
    	output.close();
  	}
}


Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Reading and Writing Student Info With a File

Posted 04 December 2011 - 11:52 PM

Scanner input = new Scanner(file);

it simply means that students.txt does not exist
Was This Post Helpful? 1
  • +
  • -

#14 kikib92  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 106
  • Joined: 26-September 11

Re: Reading and Writing Student Info With a File

Posted 05 December 2011 - 01:05 AM

I don't understand how to create the file :/
Was This Post Helpful? 0
  • +
  • -

#15 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10437
  • View blog
  • Posts: 38,651
  • Joined: 27-December 08

Re: Reading and Writing Student Info With a File

Posted 05 December 2011 - 07:28 AM

You open up your text editor, put text in it, and save it. Then have your program read in the File.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2