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.

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.