Results 1 to 12 of 12
  1. #1
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default writing to a file

    I need to use an interface to write to a file 5 times. My interface includes a book title, author ,and availability. I am to save all of this to a file 5 times where I will then create another program to read this file and perform a search.

    My question is: when I write to the file, it keeps replacing what I wrote before.

    For example:

    In my first pass: the file has title, author, availability
    In my second pass: it replaces the data from the first pass with this pass.

    How do I tell it to keep writing to a file as many times as I enter data, which then can be read later using an array?

  2. #2
    lovelesh is offline Senior Member
    Join Date
    Nov 2010
    Location
    Delhi
    Posts
    135
    Blog Entries
    1
    Rep Power
    0

    Smile

    I am very sure, something is wrong in your logic.

    Anyways, here's the workaround:

    declare a StringBuilder and append all the contents to this stringbuilder object.

    Once you are done with contents, write the stringbuilder to the file. This is like you are writing to file only once, no matter what.

    If still you feel stuck, then paste your code here, we will have a look

  3. #3
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    
    public class TryThis extends JFrame {
    
    	private JPanel panel;
    	private JButton button;
    	private JCheckBox check;
    	private JTextField bookTitle;
    	private JTextField authorField;
    	private JLabel bookLabel;
    	private JLabel authorLabel;
    	String title;
    	String author;
    	String available;
    	
    	
    	public TryThis(String str) {
    		super(str);
    
    	}
    
    	public static void main(String[] args) {
    
    		TryThis myGUI = new TryThis("Save book records");
    		myGUI.createAndShowGUI();
    		myGUI.writeTofile();
    	}
    
    	private void createAndShowGUI() {
    
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		Container contentPane = getContentPane();
    		contentPane.setLayout(new BorderLayout());
    		contentPane.setLayout(null);
    
    		JButton button = new JButton("Save");
    		button.setBounds(230, 125, 75, 20);
    		this.add(button);
    		button.addActionListener(new BookEntry());
    
    		check = new JCheckBox("Available", false);
    		check.setBounds(230, 100, 100, 20);
    		this.add(check);
    
    		bookLabel = new JLabel("Book title:");
    		bookLabel.setBounds(10, 10, 100, 20);
    		this.add(bookLabel);
    		bookTitle = new JTextField();
    		bookTitle.setBounds(120, 10, 350, 20);
    		this.add(bookTitle);
    
    		authorLabel = new JLabel("Author:");
    		authorLabel.setBounds(10, 50, 100, 20);
    		this.add(authorLabel);
    		authorField = new JTextField();
    		authorField.setBounds(120, 50, 350, 20);
    		this.add(authorField);
    
    		setSize(500, 200);
    
    		setVisible(true);
    
    	}
    
    	public class BookEntry implements ActionListener {
    		public void actionPerformed(ActionEvent ev) {
    			title = bookTitle.getText();
    			author = authorField.getText();
    			System.out.println(title);
    			System.out.println(author);
    			if (check.isSelected()) {
    				available="available";
    				
    			} else {
    				available="not available";
    				
    				}
    			System.out.println(available);
    			}
    
    		}
    	 
    	public void writeTofile() {
    		
    		
    			   StringBuilder result = new StringBuilder();        
    			   result.append(title);
    			   result.append(author);
    			   result.append(available);
    		
    		FileReader input = null; // output connection stream
    		FileWriter output = null;  // output chain stream
    		
    		try { // all the I/O stuff must be a in try/catch
    		File file = new File("book.txt");
    		if(!file.exists()){
    			file.createNewFile();
    			System.out.println("new file:" + file);
    		}
    		    
    		    output = new FileWriter("book.txt");
    		    
    		    output.write(result.toString());
    		       
    		
    	}
    		catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}
    	}
    		}
    we never covered StringBuilder in the seminar but it makes sense when I tried Googling it. However, it doesn't want to write anything to the file anymore.

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

    Default

    You're writing to the file at program start up before any data has been entered. Remember that Swing GUI's are event-driven and for the data to have any meaning, it has to be entered first. Perhaps you should append to the file when the user presses the button.

  5. #5
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    That makes sense and I moved everything to the ActionListener but it still replaces the text in the file with new text instead of appending it.

    Java Code:
    public class BookEntry implements ActionListener {
    		public void actionPerformed(ActionEvent ev) {
    			title = bookTitle.getText();
    			author = authorField.getText();
    			System.out.println(title);
    			System.out.println(author);
    			if (check.isSelected()) {
    				available="available";
    				
    			} else {
    				available="not available";
    				
    				}
    			System.out.println(available);
    			
    		
    			   StringBuilder result = new StringBuilder();        
    			   result.append(title);
    			   result.append(author);
    			   result.append(available);
    		
    			try { // all the I/O stuff must be a in try/catch
    		File file = new File("book.txt");
    		if(!file.exists()){
    			file.createNewFile();
    			System.out.println("new file:" + file);
    		}
    		    
    		    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    		    writer.write(result.toString());
    		    writer.close();
    		    
    		       
    		
    	}
    		catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}
    	}

  6. #6
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    Whenever you create a new object of FileWriter, it doesn't append to what's already written, it destroys all previous data and starts fresh.
    Use PrintWriter instead of BufferedWriter and create a new instance of FileOutputStream and specify "true" in the constructor to tell it to append to the file.

    http://ra4king.is-a-geek.net/javadoc...putStream.html

    Java Code:
    String fileName = "fileName.txt";
    FileOutputStream fos = new FileOutputStream(fileName,true);
    PrintWriter writer = new PrintWriter(fos);
    writer.println(data);
    //etc....

  7. #7
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    I was advised to use the following code:

    Java Code:
    public class BookEntry implements ActionListener {
    		public void actionPerformed(ActionEvent ev) {
    			title = bookTitle.getText();
    			author = authorField.getText();
    			System.out.println(title);
    			System.out.println(author);
    			if (check.isSelected()) {
    				available = "available";
    
    			} else {
    				available = "not available";
    
    			}
    			System.out.println(available);
    
    						
    			try { // all the I/O stuff must be a in try/catch
    				File file = new File("book.txt");
    				if (!file.exists()) {
    					file.createNewFile();
    					System.out.println("new file:" + file);
    				}
    				String bookRecord = title + ";" + author +";" + available + ";" + "/n";
    				
    				System.out.println(bookRecord);
    				
    				FileWriter writer = new FileWriter(file,true);
    
    				BufferedWriter buwriter = new BufferedWriter(writer);
    				buwriter.append(bookRecord);
    				writer.close();
    
    			} catch (IOException ex) {
    				ex.printStackTrace();
    			}
    		}
    	}
    However, it now does not want to write anything to the text file

  8. #8
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    Yes, that works too because you have supplied "true" as the second parameter to FileWriter, which specifies to append to the file.

  9. #9
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

    Default

    But for some reason it is not writing to the file

  10. #10
    ra4king's Avatar
    ra4king is offline Senior Member
    Join Date
    Apr 2011
    Location
    Atlanta, Georgia, US
    Posts
    396
    Rep Power
    4

    Default

    Ah that's because you forgot to call buwriter.flush() ;)

  11. #11
    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 ra4king View Post
    Ah that's because you forgot to call buwriter.flush() ;)
    And in fact you should call close on the BufferedWriter, not the FileWriter object. This will flush the BufferedWriter at the same time. It should be done in a finally block after first checking that the BufferedWriter isn't null.

  12. #12
    xyknight is offline Member
    Join Date
    Mar 2011
    Posts
    29
    Rep Power
    0

Similar Threads

  1. writing in file read from another file..
    By UJJAL DHAR in forum New To Java
    Replies: 6
    Last Post: 05-07-2010, 05:41 PM
  2. Replies: 1
    Last Post: 02-27-2010, 01:29 AM
  3. Replies: 9
    Last Post: 10-20-2009, 10:52 AM
  4. Replies: 3
    Last Post: 05-09-2009, 11:31 PM
  5. Replies: 9
    Last Post: 07-10-2008, 04:52 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
  •