I'm working with a java application and trying to modify this code so that it no longer prompts the user with the Dialog box to save a txt file. The user already uses the Dialog box to choose a directory in which to save the file at an early point in the application. So I have the JTextField path in a different class. I would like this code to call the path from the other class and then save the txt file.

//Choose where to save it, then send path to xml writer.
            JFileChooser filesave = new JFileChooser();
            FileFilter filter = new FileNameExtensionFilter("Text file", "txt");
            filesave.addChoosableFileFilter(filter);
            int ret = filesave.showSaveDialog(null);
         
            //Valid file loaded - create file
            FileWriter fstream = null;
            if (ret == JFileChooser.APPROVE_OPTION) {
                if (filesave.getSelectedFile().getName().contains(".txt")) {
                    fstream = new FileWriter(filesave.getSelectedFile().getPath());
                } else {
                    fstream = new FileWriter(filesave.getSelectedFile().getPath() + ".txt");
                }
            } else {
                JOptionPane.showMessageDialog(i.getFrame(), "An error occured choosing the save file.  Please try again.", "Saving File Error", JOptionPane.WARNING_MESSAGE);
            }
            BufferedWriter2 out = new BufferedWriter2(fstream);

            //Begin writing the file

Any help is greatly appreciated!!!!
Thanks

Recommended Answers

All 4 Replies

I would like this code to call the path from the other class and then save the txt file

Let me restate what you are trying to do. You have the path to the folder where you want to write the file in one place and the filename for the file in another.
To get the full path for writing the file, concatenate the path with the filename to build the full path.

Yes that is exactly what I want to do! Would you be able to show me how I would go about doing that? I've wrestled with this code for about a week now trying to do just that and haven't been able to write the code correctly.

To get a variable from another object or to call one of its methods you need a reference to that object. That is a very common problem.

To generate the full path to a file, given an object: objRef and a method that returns the path: getPath:

String fullPath = objRef.getPath() + File.separator + filename; // build full path

Thank you so much NormR1! That is just what I needed!

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.