简体   繁体   中英

Write into a file with JFileChooser

I'm trying to save a file with JFileChooser when clicking on a button. So when I'm clicking on it, the window appear as I expect, then I put the file name and save it. All work, I get my file at the exact place and in .txt as I want, but when I open it, nothing in. I've tested write and print but nothing works. So I would like to know where I'm wrong and how I should do.

Thanks !

Here is my code :

jbSave.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                String path = file.getPath() + ".txt";
                file = new File(path);
                FileWriter filewriter = new FileWriter(file.getPath(), true);
                BufferedWriter buff = new BufferedWriter(filewriter);
                PrintWriter writer = new PrintWriter(buff);
                writer.write("start");                                      
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }       
    }           
});

Just to add more details or alternatives to this answer , you can use a try-with-resource block and let the JVM handle closing (and flushing) the writer for you.

try(PrintWriter writer = ...))
{
    writer.write("start");
} 
catch (IOException e) 
{
    // Handle exception.
}

Furthermore you can write an utility function to create the PrintWriter:

/**
 * Opens the file for writing, creating the file if it doesn't exist. Bytes will
 * be written to the end of the file rather than the beginning.
 *
 * The returned PrintWriter uses a BufferedWriter internally to write text to
 * the file in an efficient manner.
 *
 * @param path
 *            the path to the file
 * @param cs
 *            the charset to use for encoding
 * @return a new PrintWriter
 * @throws IOException
 *             if an I/O error occurs opening or creating the file
 * @throws SecurityException
 *             in the case of the default provider, and a security manager is
 *             installed, the checkWrite method is invoked to check write access
 *             to the file
 * @see Files#newBufferedWriter(Path, Charset, java.nio.file.OpenOption...)
 */
public static PrintWriter newAppendingPrintWriter(Path path, Charset cs) throws IOException
{
    return new PrintWriter(Files.newBufferedWriter(path, cs, CREATE, APPEND, WRITE));
}

Another possibility is to use Files.write() if all data can be written in one operation:

try 
{
    byte[] bytes = "start".getBytes(StandardCharsets.UTF_8);
    Files.write(file.toPath(), bytes)
} 
catch (IOException e) 
{
    // Handle exception.
}

The problem was that you did not close PrintWriter instance. You can resolve your problem by just closing the PrintWriter after you finish writing like this :

writer.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM