简体   繁体   English

无法使用Java写入文件

[英]unable to write to file with java

I have wrote a simple java GUI program to write the content of a text area into a file: 我编写了一个简单的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());
                }

            }
        });
    }
}

Note that the input source is in utf-8 (chinese character) and i am able to print out correctly. 请注意,输入源使用utf-8(中文字符),并且我能够正确打印出。 However, the result.txt file is empty. 但是,result.txt文件为空。 Even if i try bw.write("asdf") it's still empty. 即使我尝试bw.write(“ asdf”)仍然为空。

You are missing to close the BufferedWriter. 您丢失了关闭BufferedWriter。 Closing it will do the flush and close of the writer and you should see the contents in your file. 关闭它会完成编写器的刷新和关闭操作,您应该在文件中看到其中的内容。 You need to add the following. 您需要添加以下内容。

bw.close();

And here is where you need to put the 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();

Note: Ideally putting it in the finally block makes more sense because if there is an exception even then it will get 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");
               }
            }

You have to make sure that you have closed the FileWriter, or in your case, the buffered writer. 您必须确保已关闭FileWriter,或者已关闭缓冲写入器。 So all you gotta do is 所以你要做的就是

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

this will close the open buffer, and allow it to write whatever is in the buffer to the file you are creating. 这将关闭打开的缓冲区,并允许其将缓冲区中的任何内容写入正在创建的文件中。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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