我编写了一个简单的 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") 它仍然是空的。