簡體   English   中英

用JFileChooser寫入文件

[英]Write into a file with JFileChooser

我試圖在單擊按鈕時使用JFileChooser保存文件。 因此,當我單擊它時,窗口將如預期的那樣出現,然后放入文件名並保存。 一切正常,我將文件放置在正確的位置,並按需要將文件保存在.txt中,但是當我打開文件時,什么也沒進入。我已經測試過寫入和打印,但是沒有任何效果。 所以我想知道我在哪里錯了,應該怎么做。

謝謝 !

這是我的代碼:

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();
            }
        }       
    }           
});

只是為該答案添加更多詳細信息或替代方法,您可以使用try-with-resource塊,讓JVM為您關閉(並刷新)編寫器。

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

此外,您可以編寫一個實用程序函數來創建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));
}

如果所有數據都可以在一個操作中寫入,則另一種可能性是使用Files.write()

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

問題是您沒有關閉PrintWriter實例。 完成這樣的編寫后,只需關閉PrintWriter即可解決問題:

writer.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM