【问题标题】:unable to write to file with java无法用java写入文件
【发布时间】:2013-08-11 05:00:21
【问题描述】:

我写了一个简单的java GUI程序来将文本区域的内容写入文件:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;

public class Convert {
    public static void main(String[] args) {
        new MyFrame();
    }
}


class MyFrame extends JFrame{
    JPanel panel = new JPanel();
    JButton button = new JButton("Convert");
    JTextArea textArea = new JTextArea(500, 400);
    String fileName = "result.txt";

    MyFrame() {
        super("converter");
        setVisible(true);
        setBounds(100, 100, 500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(panel);
        panel.setLayout(null);

        panel.add(button);
        button.setLocation(0, 0);
        button.setSize(this.getBounds().width, 100);

        panel.add(textArea);
        textArea.setEditable(true);
        textArea.setLocation(0, 100);
        textArea.setSize(this.getBounds().width, this.getBounds().height - 100);

        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {

                try {
                    File file = new File(fileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }

                    FileWriter fw = new FileWriter(file);
                    BufferedWriter bw = new BufferedWriter(fw);

                    String text = textArea.getText();
                    textArea.setText("");
                    Scanner scanner = new Scanner(text);

                    while (scanner.hasNextLine()) {

                        String line = scanner.nextLine();
                        byte[] utf8 = line.getBytes("UTF-8");
                        line = new String(utf8, "UTF-8");

                        bw.write(line);
                        System.out.println(line);
                    }

                }

                catch (Exception e) {
                    System.out.print(e.getMessage());
                }

            }
        });
    }
}

请注意,输入源是 utf-8(中文字符),我可以正确打印出来。但是,result.txt 文件是空的。即使我尝试 bw.write("asdf") 它仍然是空的。

【问题讨论】:

  • 或者您可以在while 循环内调用flush(),将flush 取出buffer 的内容,正如thread 中所引用的那样:-)

标签: java swing file io


【解决方案1】:

您缺少关闭 BufferedWriter。关闭它将执行写入器的刷新和关闭,您应该会看到文件中的内容。您需要添加以下内容。

bw.close();

这里是你需要放置 close() 的地方:

                while (scanner.hasNextLine()) {

                    String line = scanner.nextLine();
                    byte[] utf8 = line.getBytes("UTF-8");
                    line = new String(utf8, "UTF-8");

                    bw.write(line);
                    System.out.println(line);
                }
                // close the buffered
                bw.close();

注意:理想情况下将它放在 finally 块中更有意义,因为即使有异常,它也会接近。

  try {
                File file = new File(fileName);
                if (!file.exists()) {
                    file.createNewFile();
                }

                FileWriter fw = new FileWriter(file);
                BufferedWriter bw = new BufferedWriter(fw);

                String text = textArea.getText();
                textArea.setText("");
                Scanner scanner = new Scanner(text);

                while (scanner.hasNextLine()) {

                    String line = scanner.nextLine();
                    byte[] utf8 = line.getBytes("UTF-8");
                    line = new String(utf8, "UTF-8");

                    bw.write(line);
                    System.out.println(line);
                }

            }

            catch (Exception e) {
                System.out.print(e.getMessage());
            } finally {
                try {
                    bw.close();
               } catch (Exception e) {
                System.out.print("Exception while closing the bw");
               }
            }

【讨论】:

  • 什么时候?每次写入后?
  • @OMGPOP 是的。如果你在while中这样做,它会在第一次写入后关闭它,随后的写入会抛出错误。
  • 你把 bw.write() 放在最后一行了吗?
  • 当我在每次写完后把它写下来,我只写第一行。但如果我把它放在while循环之外,文件又是空的
  • 原来是其他问题。现在好了
【解决方案2】:

你必须确保你已经关闭了 FileWriter,或者在你的情况下,缓冲的 writer。所以你要做的就是

bw.write(line);
System.out.println(line);
bw.close();

这将关闭打开的缓冲区,并允许它将缓冲区中的任何内容写入您正在创建的文件中。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多