Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: java file handling

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question java file handling

    Hi all, I have a problem with a java program writing to files. I can get the main class and tester programs running (poorly) but I'm stuck trying to write user id no and 3 grade marks each to a seperate file,
    this file is then supposed to be able to calculate the average for each id. I then have to sort each user into 2 other files by gender.
    Could anyone have a look at my code so far and give me a few pointers where to go next. I have pieces of code that might do this but no idea where to put it to get results
    Here is my code so far///////////
     import java.io.*;
     import java.io.PrintWriter; 
     public class Student
     {
       private String Lno ;//studentID;
    	private String FName;//first name
    	private String MiddleN;//middle name
    	private String LastN;//lastname
    	private double Mark1;
    	private double Mark2;
    	private double Mark3;
    	private String gender;
     
    	private String name;                 // to get Student's name./might need it yet
       public double test1, test2, test3;   // Grades on three tests.
     
               Student(String theName) {
                    // Constructor for Student objects;
                    // provides a name for the Student.
                  name = theName;
               }
     
               public String getName() {
                    // Accessor method for reading value of private
                    // instance variable, name.
                  return name;
               }
     
               public double getAverage() { 
                    // Compute average test grade.
                  return (Mark1 + Mark2 + Mark3) / 3;
               }
     
     
    	//Default Constructor
    	// public Student()
    //    {
    // 	}
    	public Student()
    	 {
    	   Lno = "Lxxxxxxx";// studentID
    		FName = "";
    		MiddleN = "";
    		LastN = "";
    		Mark1 = 0.0;
    		Mark2 = 0.0;
    		Mark3 = 0.0;      
    		gender = "";
    	}
     
    	//Set Name
    	public void setNames(String name) throws IOException
     
    	 {
    		String[] nameSplit = name.split(" ");
    		FName = nameSplit[0];
    		LastN = nameSplit[nameSplit.length - 1];
    		if (nameSplit[1] != LastN)
    		 {
    			MiddleN = nameSplit[1];
    		}
    	}
     
    	//Set studentID 
    	public void setLno(String id)throws Exception//student id L number
    	 {
    		//Check that characters are integers (8 total)
    		int numbers = 0;
    		for(int i=1; i<9; i++)//start at 1, leave the first one(0) for "L"
    		 {
    			if (Character.isDigit(id.charAt(i)))//put numbers from 1 to 8, check character is a digit
     
    				numbers++;
    		 }
    // 		for(int i=5; i<9; i++)//numers from 5 to 8
    // 		 {
    // 			if (Character.isDigit(id.charAt(i)))//				numbers++;
    // 		}
    		//Check that 9 char long, and contains all numbers
    		//char hyphen = id.charAt(4);//put a hyphen in the middle
    		if (id.length() == 9  && numbers == 8)
    		 {
    			 Lno = id;// studentID
    			System.out.println("Valid");
    		}
    		else 
    		{
    			System.out.println("studentID is not valid. ");
    		}
    	}
     
    	//Get methods
    	public String getFullName()
    	 {
    		String fullName;
    		if (MiddleN.matches(""))
    		 {
    			fullName = FName + " " + LastN;
    		}
    		else {
    			fullName = FName + " " + MiddleN +  " " + LastN;
    		}
    		return fullName;
    	}
     
    	public String getstudentID()
    	 {
    		return Lno;//studentID;
    	}
     
    	public void  getgender(String female, String Female)
    	{
    		if(gender ==female || gender ==Female)
    			System.out.print("female");
    			else
    				System.out.print("male");
    	}
    	// public String getwrite()
    // 	{
    // 		return Student();
    // 	}
     
    	//toString method
    	public String toString()
    	 {
    		return "studentID" + Lno + "Name: " + FName + " " + MiddleN + " " + LastN + "Mark " + Mark1 + "Mark" + Mark2 + "Mark" + Mark3 + "Gender " + gender + "\n";
    	}
    }
    and the tester/////////
    import java.util.InputMismatchException;
    import java.io.*;
    import java.util.Scanner;
       public class WriteStudentData
       {
     
          public static void main(String[] args) throws Exception
          {
             Scanner keyIn=new Scanner (System.in);
             Student s = new Student();
     
     
     
     
             //Create a file object called student.txt
                java.io.File file = new java.io.File("student.txt");             
             // Create file
                java.io.PrintWriter output = new java.io.PrintWriter(file);   
             // Write  to the student textfile
     
                output.println("L00012322 Mary Smith 99.1 47.5 66.5 Female");
                output.println("L00022211 Paul O Donnell 17.5 99.1 47.5 Male");
                output.println("L00033333 Anne Marie McLaughlin 100 100 100 Female");
                output.println("L00033345 Sean Dunne 99.1 99.1 0 Male");
             // Close the file
                output.close();
                try{//open a named file (Student)							            
                   FileInputStream fstream = new FileInputStream("student.txt");
     
                // Get the object of DataInputStream
                   DataInputStream in = new DataInputStream(fstream);
                   BufferedReader br = new BufferedReader(new InputStreamReader(in));
                   String strLine;
                //Read File Line By Line
                   while ((strLine = br.readLine()) != null)  
    					 {
                   // Print the content on the console
                      System.out.println (strLine);
                    }
                //Close the input stream
                   in.close();
                }
                   catch (Exception e){//Catch exception if any
                      System.err.println("Error: " + e.getMessage());
                }
    			try
    			{
        		String data = "S123456 John Paul Smith, 100, 100, 100, Male\n";
     
        		    		if(!file.exists())
    			{
        			file.createNewFile();//if file doesnt exists, then create it. if it exists write to it/overwrite it
     
        		}
        		//true = append file
         	   	FileWriter fileWriter = new FileWriter(file.getName(),true);
        	        BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
        	        bufferWriter.write(data);
        	        bufferWriter.close();
     
    	        System.out.println("\n You have added a new student to file \n" +data +"\n\n");
     			output.close();
     
          	}
    			catch(IOException e){
        		  e.printStackTrace();
    			 }
     
    			System.out.println("\tPlease select option: ");
     
    		int option=0;
    		do
    		{
    			//display menu
    			System.out.println("\n\t\t----Options ----");//maybe add lno here
    			System.out.println("\t1. Add Student" );
    			System.out.println("\t2. Find Average ");
    			System.out.println("\t3. Find female");
    			System.out.println("\t4. Find Male");
    			System.out.println("\t5. Information on file setup");//maybe view files
     
    			System.out.println("\tQ. Quit");
    			option = keyIn.nextInt();
    			switch(option)
     
     
     
    			{
    			case 1:
     					int method=0;
    				do
    				{
     
               try
    			  {
                   System.out.print ("\tENTER STUDENT DETAILS\n\n");
     
    					System.out.print ("\tEnter Student L Number\n\n");
                   String Lno = keyIn.next(); 
    					//while(!keyIn.hasNextLine ([A-Z a_z]);
    				  // if (!keyIn.hasNextLine()) 
    					//throw new BadDataException();
    					System.out.print ("\t Eenter Student first Name\n\n");
                   String FName = keyIn.next();
    					// if (!keyIn.hasNextLine()) 
    					//throw new BadDataException("Student first name only");*/
    					System.out.print ("\t Enter Student Middle Name\n\n");
                   String MiddleN = keyIn.next();
    					// if (!keyIn.hasNextLine()) 
    					//throw new BadDataException("Student Middle name if he has one");*/
    					System.out.print ("\t Enter Student Last Name\n\n");
                   String LastN = keyIn.next();
    					// if (!keyIn.hasNextLine()) 
    					//throw new BadDataException("Student Last name only");*/
    					System.out.print ("\t Enter Students Mark1 result\n\n");
                   double Mark1 = keyIn.nextDouble();
    					System.out.print ("\t Enter Students Mark2 result\n\n");
                   double Mark2 = keyIn.nextDouble();
    					System.out.print ("\t Enter Student Mark3 result\n\n");
                   double Mark3 = keyIn.nextDouble(); 
    					System.out.printf("\t Enter Students Gender\n\n");
                   String data = keyIn.next();
    	           //if file doesnt exists, then create it
                  if(!file.exists())
    				  {// if it exists write to it else write a new file
                     file.createNewFile();
    	           }            
                //true = append file
                  FileWriter fileWriter = new FileWriter(file.getName(),true);
                  PrintWriter p = new PrintWriter(fileWriter);
    			  		// p.write(Lno);
    // 					p.write(" "+FName);
    // 					p.write(" "+MiddleN);
    // 					p.write(" "+LastN);
    // 					p.write(" "+Mark1);
    // 					p.write(" "+Mark2);
    // 					p.write(" "+Mark3);
    // 					p.write(" "+data);
    //                p.close();
     
                   System.out.println(" new student  added to record");            
               		} 
                   catch(Exception e)
    					{
                   System.out.print("The  information you have entered is incorrect\n");
    					}
    					}while(method != 0);
    					//System.exit(0);		
    					break;							
    				case 2:
    			//  Create a file object called Average.txt
    			  java.io.File file2 = new java.io.File("Average.txt");
    			  // Create file
    			 java.io.PrintWriter output2 = new java.io.PrintWriter(file2);	
    			 output2.println("45"); //p.write(Lno);
    			  output2.close(); 
     
    				break;	
    				case 3:
    			//  Create a file object called Male.tx
    			  java.io.File file3 = new java.io.File("Male.txt"); 
    			 // Create file
     			  java.io.PrintWriter output3 = new java.io.PrintWriter(file3);
    			 output3.println("45");
    			  output3.close(); 
     
    				break;
    				case 4:
    				//  Create a file object called Female.txt
    			  java.io.File file4 = new java.io.File("Female.txt"); 
    			  // Create file
     			  java.io.PrintWriter output4 = new java.io.PrintWriter(file4);
    			 output4.println("45");
    			  output.close(); 
     
    				break;	
    				// case 5://this can be done without/ maybe
    // 				System.out.println("\t File created\n");
    // 				System.out.println("\t File Readable " +  file.canRead());
    // 				System.out.println("\t File Writeable " +  file.canWrite());
    // 				System.out.println("\t Is a File  " +  file.isFile());
    // 				System.out.println("\t Is Hidden " +  file.isHidden());
    // 				System.out.println("\t Last Modified " +  file.lastModified());
    // 				System.out.println("\t File Size " +  file.length()+"\n");
    // 				file.renameTo(new File("studentFile"));			
    // 				break;								
    				default: 
    			}//end switch
     
    		}while(option != 0);
     
    			   boolean done = false;
     
     
    				              // System.out.print("Your information is incorrect");
           //  PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter(s)));
       		// printwriter is used to write characters to a file used for a while ie println print in system.out.print to screen
    			// BufferedWriter gathers a bunch of charaters and write them all at one time
    			//FileWriter is used to write stream of charaters to a file thats all it does"writes to the file that has been created
     
     
                }   
             }
    I seem to be doing a lot of coding without getting many results, I hope someone can help me.
    Thank you MartinMc


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: java file handling

    For easier testing that does not require user input, change the definition for the Scanner class to have ALL the input data that is needed to execute the code. For example:
             Scanner keyIn=new Scanner ("put the required input here\nAnother line\n"); //System.in);
    With that definition (with the correct values) the tester will not have to enter any data
    and the data the program reads will be the same for all testers.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: java file handling

    Thanks for that Norm but I need to input diffrent querys, 1 to list students and details, 1 to get student numbers with averages and 1 (or 2) to get listings by gender
    Quote Originally Posted by Norm View Post
    For easier testing that does not require user input, change the definition for the Scanner class to have ALL the input data that is needed to execute the code. For example:
             Scanner keyIn=new Scanner ("put the required input here\nAnother line\n"); //System.in);
    With that definition (with the correct values) the tester will not have to enter any data
    and the data the program reads will be the same for all testers.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: java file handling

    need to input diffrent querys
    There is no limitation on the length of the the String used in the Scanner class's constructor. You can preload hundreds of responses. Use the \n character where there should be a newline character for a call to nextLine().

    The advantage for you if you want help testing your code is that more people will be willing to run a test if they are not required to make multiple entries to the program.
    AND the data that is entered will be the same for everyone incase there are problems that only occur with certain data.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: java file handling

    Thanks for that Norm, I think I understand but now Im not sure where to put that part of the code, Ive had problems trying to input all together, thats why I put them in seperate statements

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: java file handling

    I'm not sure I understand what you just said.
    Are you still having problems or have you solved them?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: java file handling

    No, still having problems but thanks for making the effort. Ill have to give up on it,

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: java file handling

    Without the program's input being provided, it will be hard to find anyone to test it.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 2
    Last Post: August 3rd, 2011, 11:13 AM
  2. Java: Handling cookies when logging in with POST
    By cloakbot in forum What's Wrong With My Code?
    Replies: 0
    Last Post: June 16th, 2010, 04:31 PM
  3. Regarding File Handling
    By ravjot28 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: March 1st, 2010, 07:45 PM
  4. File handling in java
    By srikanth in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: February 22nd, 2010, 02:11 AM
  5. Output String Handling in Java
    By merry in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 21st, 2010, 09:59 PM