我写了一个简单的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”)它仍然是空的。
答案 0 :(得分:3)
您缺少关闭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");
}
}
答案 1 :(得分:2)
您必须确保已关闭FileWriter,或者在您的情况下,已关闭缓冲的编写器。所以你要做的就是
bw.write(line);
System.out.println(line);
bw.close();
这将关闭打开的缓冲区,并允许它将缓冲区中的任何内容写入您正在创建的文件中。
希望这有帮助!