Page 1 of 2 12 LastLast
Results 1 to 20 of 29
  1. #1
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default NEW to writing/saving to a file

    this is the first time in my class they have addressed writing to a txt file. the examples they walked me though involve having 3 buttons on the gui, an "open file" button, a "enter data" and a "close file" button. i sort of understand that, using JFileChooser. however, the application i am supplied with that i need to finish has one button basically a "enter" button, and the files are to automatically go to the appropriate txt file. i am BRAND new at this, and looking at code something like this:

    Java Code:
    private void reserveCarJButtonActionPerformed( ActionEvent event )
       {
          File reserveFile = new File ( "reservations.txt" );
          
          try 
          {
    	      FileReader reserveFile = new FileReader ( "reservations.txt" )
    	      input = new BufferedReader ( inputFile );
    	  }
          
          
          
          
       } // end method reserveCarJButtonActionPerformed
    am i even close?

    i really am having trouble wrapping my head around the process of writing/reading to another file for some reason, so very basic answers are helpful.

  2. #2
    UJJAL DHAR is offline Senior Member
    Join Date
    Apr 2010
    Location
    Dhaka,Bangladesh
    Posts
    180
    Rep Power
    0

    Default

    use this code to save file....


    Java Code:
    void Save() {
        FileDialog file = new FileDialog (Compare.this, "Save File", FileDialog.SAVE);
        file.show();
        String saveFile;
        if ((saveFile = file.getFile()) != null) {
          String filename = file.getDirectory() + saveFile ;
          setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
          File f = new File (filename);
          try {
            FileWriter fw = new FileWriter (f);
    
            fw.write (jtextpane3.getText());
            fw.close ();
    
          } catch (IOException exc) {
    
          }
          setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
      }

  3. #3
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    thanks for you post, but i need to learn how and why thing need to to what they to. i have a predesigned gui form supplied for me, and instructions. the gui form has a date spinner, name textfield, and a reserveCar button, the reserve car button code has an empty:
    Java Code:
    private void reserveCarJButtonActionPerformed( ActionEvent event )
       {
    
        }
    and i am supposed to input the code required to

    1. open the file to read from (reservations.txt)
    2. retrieve the date
    3. read text from the file
    4.write to the text file

    i have a paragraph of more detailed instructions under each one, but some of it is just over my head it seems. if anyone wants to help me take this one step at a time without just giving the answers, id be very appreciative.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Post the first paragraph that has instructions that you don't understand, and highlight and comment on the confusing parts.

  5. #5
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    it says:

    Open a file to read from:
    In the actionperformed method create a new FILE object reserveFile for the reservations.txt. Then, add a TRY block. inside the try block, create a FileReader by passing the reserveFile to its constructor. Use FileReader to initialize BufferedReader input.

    so i came up with this:

    Java Code:
    private void reserveCarJButtonActionPerformed( ActionEvent event )
       {
          File reserveFile = new File ( "reservations.txt" );
          
          try 
          {
    	      FileReader reserveFile = new FileReader ( "reservations.txt" )
    	      input = new BufferedReader ( reserveFile );
          }
    but i have no idea whether im even close so far.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    The first thing to do to see whether your close is to compile your code and be sure there are no compile errors. Your current code may have some since you seem to be using a variable name, reserveFile, twice. You're also not using the File variable in your FileReader constructor as you should be doing.

    I suggest that you create a separate small non-GUI program just for testing out file reading code. Once you get the kinks ironed out, then you'll be able to add it into your GUI.

    But even before that, find out where Java is looking to find files by creating and running this:
    Java Code:
    public class WhereUserDir {
       public static void main(String[] args) {
          System.out.println("Where is Java looking for the file: " + System.getProperty("user.dir"));
       }
    }

    Then you'll have a better idea of the path String you'll need to find your reservations.txt file. When I run this, my program returns:
    Java Code:
    Where is Java looking for the file: C:\Users\Pete\Documents\workspace\Pete 2010
    So I know that to find my reservations.txt file, I have to use a file path String like so:
    Java Code:
    File reserveFile = new File("src/yr2010/m12/a/reservations.txt");
    So if it were me, I'd create a small program that looks like so:
    Java Code:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class TestFileRead {
       public static void main(String[] args) {
          // your file path String will be different!
          File reserveFile = new File("src/yr2010/m12/a/reservations.txt");
          
          try {         
             // use the File variable above to construct a FileReader
             FileReader reserveFileReader = new FileReader(reserveFile);
             
             // use the FileReader to construct a BufferedReader
             BufferedReader input = new BufferedReader(reserveFileReader);
             
             String line = "";
             while ((line = input.readLine()) != null) {
                System.out.println(line);
             }
          } catch (FileNotFoundException e) {
             e.printStackTrace();
          } catch (IOException e) {
             e.printStackTrace();
          }
       }
    }

  7. #7
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    let me speak to the .txt file location, then i will continue studying the rest of your post more.

    the .txt file is located in the same folder as the .java file i am working on, does that mean i can simply used the path of reservations.txt or no?

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by hayden06f4i View Post
    let me speak to the .txt file location, then i will continue studying the rest of your post more.

    the .txt file is located in the same folder as the .java file i am working on, does that mean i can simply used the path of reservations.txt or no?
    Run my small program and this will provide your answer (likely "no"), and the solution.

  9. #9
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Run my small program and this will provide your answer (likely "no"), and the solution.

    i made your little program:
    Java Code:
    public class WhereUserDir {
       public static void main(String[] args) {
          System.out.println("Where is Java looking for the file: " + System.getProperty("user.dir"));
       }
    }
    and put it in the folder with my CarReservation and reservations.txt files, and ran it here is what i got:

    C:\simplyjava\CarReservation

    which is the folder that CarReservation.java and reservation.txt are in currently.

    i feel more confused now that before, isn't that what i wanted? its looking for the files in the same folder as the program is running in....right?

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by hayden06f4i View Post
    i made your little program:
    Java Code:
    public class WhereUserDir {
       public static void main(String[] args) {
          System.out.println("Where is Java looking for the file: " + System.getProperty("user.dir"));
       }
    }
    and put it in the folder with my CarReservation and reservations.txt files, and ran it here is what i got:

    C:\simplyjava\CarReservation

    which is the folder that CarReservation.java and reservation.txt are in currently.

    i feel more confused now that before, isn't that what i wanted? its looking for the files in the same folder as the program is running in....right?
    Not necessarily. If I am not going to change my document files/resources and plan to package them with my class files in a jar, I often have them in a subdirectory off of the class files, but if I am going to be changing them and thus am not going to package them in the jar, then I can have them anywhere -- as long as my program can find them. This is probably more than you want to know right now, but the bottom line is, you can place your text files anywhere as long as your program can find them. The user.dir output will tell you where your java program is looking to find your file. You can use this information to find out where your document file is in relationship to the user.dir and then write your path String appropriately.

    So, can you write a small program that reads and spits out the text lines held in the reservations.txt file?

  11. #11
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post

    So, can you write a small program that reads and spits out the text lines held in the reservations.txt file?
    there is nothing in the .txt file, because i can't figure out how to write to it yet...

    i guess my lack of knowledge of java is making it hard for me to articulate what im trying to do....

    here are the directions for the first 2 steps,

    1. create a new FILE object reserveFile for the file reservations.txt. then add a try block. Inside the TRY block, create a FileReader by passing the reserveFile to its constructor. use this FileReader to initialize BufferedReader input.
    2. Retrieving selected date. for this application, you should store in reservations.txt the date selected, including the day month and year. to access this information, you will need to extract text from the selected Date in dateJspinner. coding adding code to the try block. your code should retrive the selected value in dateJspinner, use a cast to convert it to a date object and store this object in Date fullDate. Convert the Date object to a String and store it in string currentDate. use the substring method to extract the first 10 characters from currentDate, and store this substring in string monthday.use the substring method to extract characters at indices 24-27 (inclusive) ffrom currentDate and store this substring in year. this substring contains the current year. append monthday and year, separated by a space, and store the sesulting string in currentDate

    heres where im at:

    Java Code:
    private void reserveCarJButtonActionPerformed( ActionEvent event )
       {
          File reserveFile = new File ( "reservations.txt" );
          
          try 
          {
    	      //construct FileReader
    	      FileReader reserveFileReader = new FileReader ( reserveFile );
    	      
    	      //construct BufferedReader
    	      BufferedReader input = new BufferedReader ( reserveFileReader );
    	      
    	      // get selected date
    		  Date fullDate = ( Date ) dateJSpinner.getValue();
    		  String currentDate = fullDate.toString();
    now i start with substring methods, correct? am i correct so far?

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I am a little confused by your instructions as they're for two completely separate aspects of file handling, reading and writing: Direction 1 tells you some of the steps needed to create a way to read in the data held by your text file whild Direction 2 tells you some of the steps needed to get Date information from your JSpinner and then massage it somewhat so that it can be written to a String that will be stored in a text file. But it seems to me that these directions should be used to create different methods -- one to read in the file, and the other to write to the file -- unless I'm misreading things.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Also, since you don't appear to be allowed to use the SimpleDateFormat class, consider creating in a method

    Java Code:
    public String dateToString(Date date) {
      //... your conversion code goes here
    }

    and perhaps, if your program needs it

    Java Code:
    public Date stringToDate(String dateString) {
      //.... again your conversion code goes here
    }
    and then testing your use of subString to see if it is working correctly.

  14. #14
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    initial instructions:

    Create an application that allows a user to reserve a car for a specified day. The car reservation company can rent out only four cars per day. Let the application allow the user to specify a certain day. If four cars have already been reserved for that day, the indicate to the user that no vehicles are available. Reservations are stored in reservations.txt

    xtra info from me:
    the GUI is written, which everything done except an empty reserveCarJButtonActionPerformed method. i need to finish the GUI.

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Further:

    Quote Originally Posted by hayden06f4i View Post
    there is nothing in the .txt file, because i can't figure out how to write to it yet...
    You can always put information in it, even useless information, just to test that you can read lines of Strings from it OK.


    heres where im at:

    Java Code:
    private void reserveCarJButtonActionPerformed( ActionEvent event )
       {
          File reserveFile = new File ( "reservations.txt" );
          
          try 
          {
    	      //construct FileReader
    	      FileReader reserveFileReader = new FileReader ( reserveFile );
    	      
    	      //construct BufferedReader
    	      BufferedReader input = new BufferedReader ( reserveFileReader );
    	      
    [color="red"][b]	      // get selected date
    		  Date fullDate = ( Date ) dateJSpinner.getValue();
    		  String currentDate = fullDate.toString();[/b][/color][b][/b]
    now i start with substring methods, correct? am i correct so far?
    As per my posts above, your code in red does not belong in this reserveCarJButtonActionPerformed method but belongs elsewhere in the program. This method is for reading in data from the text file, not for extracting information from the JSpinner.

  16. #16
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    if thats the case, then why is there only 1 button that says "reserve car" that im assuming is eventually set so that when you click "reserve car" it reads the date, and nametextfield, and writes them to the .txt file. doesn't all of the reading and writing need to be inside the event handler?

  17. #17
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    PMed you the full list of instructions maybe you help me understand better with the full instructions.

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by hayden06f4i View Post
    PMed you the full list of instructions maybe you help me understand better with the full instructions.
    Post them here, not in a PM. It's best to share all information with all users.

  19. #19
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default full instructions

    here are the full instructions for the program






  20. #20
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    based on the full instructions i posted above, i just followed through from start to finish with what i "thought" they wanted, whether or not i was doing it correctly. feel free to pick this all apart, because, obviously it doesn't run correctly, but here was my best guess.

    Java Code:
     private void reserveCarJButtonActionPerformed( ActionEvent event )
       {
          File reserveFile = new File ( "reservations.txt" );
          
          try 
          {
    	      //construct FileReader
    	      FileReader reserveFileReader = new FileReader ( reserveFile );
    	      
    	      //construct BufferedReader
    	      BufferedReader input = new BufferedReader ( reserveFileReader );
    	      
    	      // get selected date
    		  Date fullDate = ( Date ) dateJSpinner.getValue();
    		  String currentDate = fullDate.toString();
    		  
    		  //extract first 10 characters from currentDate
    		  String monthDay = currentDate.substring (1,10);
    		  
    		  //extract year from currentDate
    		  String year = currentDate.substring (24-27);
    		  
    		  //append monthDay and Year and store in the String currentDate
    		   currentDate = ( monthDay + "," + year );
    		  
    		  int dateCount = 1; // count the number of  reservations per day (max 4)
    		  String contents = input.readLine();
    		  
    		  // check if too many cars are reserved
    		  while ( contents != null )
      		  {
                // check reservation date
    			if ( contents.equals( currentDate ) )
    			{
    				// check reservation number
    				if ( dateCount < 4 )
    				{
    					dateCount++;
    				}
    				else
    				{
    					JOptionPane.showMessageDialog ( this, "No more cars are available.",
    		   			"Out Of Cars", JOptionPane.ERROR_MESSAGE );
    		   			
    		   			// disable reserveCarJButton because no cars are left
    		   			reserveCarJButton.setEnabled ( false );
    		   			
    				}// end inner if/else
    			 }// end outer if
    		  } // end while
    		  
    		  // close the file
    		  output.close();
    		  
    		  // open reservations.txt file for writing
    		  FileWriter reserveFileWriter = new FileWriter ( "reservations.txt" );
    		  output = new PrintWriter ( reserveFile );
    		  
    		  // write currentDate to file
    		  output.println ( currentDate );
    		  
    		  //write name to file
    		  output.println ( nameJTextField.getText() );
    		  
    		  JOptionPane.showMessageDialog (this, "Your car has been reserved.");
    		  
    		  //close file
    		  output.close();
    		  
    	   } //end try
           catch ( IOException exception )
           {
    	      JOptionPane.showMessageDialog ( this, "IOException occurred." ); 
    	      dateJSpinner.setEnabled ( false );
    	      reserveCarJButton.setEnabled ( false );
    	   }
           nameJTextField.setText ( "" );	
          
       } // end method reserveCarJButtonActionPerformed

Page 1 of 2 12 LastLast

Similar Threads

  1. Saving a file in a gui
    By rav in forum AWT / Swing
    Replies: 9
    Last Post: 07-07-2010, 05:27 PM
  2. Saving Several arraylists into one file?
    By Cemi in forum New To Java
    Replies: 2
    Last Post: 04-26-2010, 02:04 PM
  3. Replies: 1
    Last Post: 02-27-2010, 01:29 AM
  4. Replies: 8
    Last Post: 02-18-2010, 12:54 PM
  5. Saving to a Text File
    By jadaleus in forum Advanced Java
    Replies: 2
    Last Post: 10-17-2008, 06:50 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
  •