954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

BufferedWriter not writing?

Hi all,

I'm new here and a little flummoxed by this problem. I am working through the process of creating a notepad type program in java to get a little more experience with the language. My save functionality is not working. This is not unexpected; the part that is really throwing me for a loop is that I am not getting any exception or indication that it doesn't work other than the fact that the file in question is empty. The pertinent code:

public void saveTheFile() {
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(new File("C:\\workspace\\Utilities\\bin\\xmlEditor\\xml"));
		chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
			public boolean accept(File f) {
				return f.getName().toLowerCase().endsWith(".xml")
  	            	|| f.isDirectory();
  	      	}

  	      	public String getDescription() {
  	      		return "XML Files";
  	      	}
		});
		
		if (chooser.showSaveDialog(new JFrame()) == JFileChooser.APPROVE_OPTION) {
			fileName = chooser.getSelectedFile().getName();
			try {
			    chooser.getSelectedFile().createNewFile();
			    BufferedWriter outgoing = new BufferedWriter(new FileWriter(fileName));
			    System.out.println(chooser.getSelectedFile().canWrite());
			    System.out.println(contents.toString());
			    outgoing.write(contents.toString());
			    outgoing.close();
			} catch (Exception e){
				e.printStackTrace();
			}
		}
	}


My System.out.println statements on 20 and 21 are giving me the output I would expect - namely true and the contents of the file. contents is a StringBuilder , btw.

iamchuckb
Newbie Poster
2 posts since Nov 2010
Reputation Points: 10
Solved Threads: 0
 

Hello once again everybody.

I finally found the mistake myself. It figures that once I took the time to sign up on a forum and post it, it would finally come to me. The problem with my above code was line 19 where I created the FileWriter with the fileName string. fileName was populated using chooser.getSelectedFile().getName() which returns the naked name of the file, sans path. That is how I want the fileName variable populated, so I changed line 19 needs to the following:

BufferedWriter outgoing = new BufferedWriter(new FileWriter(chooser.getSelectedFile().getPath()));


Hope nobody has spent time on this yet!

iamchuckb
Newbie Poster
2 posts since Nov 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: