亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用JFileChooser寫入文件

用JFileChooser寫入文件

慕絲7291255 2021-04-14 13:46:28
我正在嘗試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();            }        }           }           });
查看完整描述

2 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

問題是您沒有關閉PrintWriter實例。您可以通過PrintWriter在完成這樣的編寫后關閉來解決您的問題:

writer.close();


查看完整回答
反對 回復 2021-04-28
?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

只是為該答案添加更多詳細信息或替代方法,您可以使用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.

}


查看完整回答
反對 回復 2021-04-28
  • 2 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號