[英]unable to write to file with java
我編寫了一個簡單的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”)仍然為空。
您丟失了關閉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");
}
}
您必須確保已關閉FileWriter,或者已關閉緩沖寫入器。 所以你要做的就是
bw.write(line);
System.out.println(line);
bw.close();
這將關閉打開的緩沖區,並允許其將緩沖區中的任何內容寫入正在創建的文件中。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.