我的小程序在大多数情况下都可以工作,但它有些问题。我的代码通知用户他们需要输入文件名 WORKS. 但这就是它的结束,因为通知用户他们没有输入文本不起作用,将文本写入文件也不起作用。
就好像我的程序中途中断了。我希望有人可以看看代码,让我知道任何明显的事情。我已经盯着它看了 6 个小时,不再相信我的眼睛了。该小程序非常基本且直接。用户在工作目录中输入一个 txt 文件的文件名,然后他们在测试字段中输入的任何内容都会写入该文件。
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
public class wwalker2 extends Applet {
Button write = new Button("WriteToFile");
Label label1 = new Label("Enter the file name:");
TextField text = new TextField(20);
Label label2 = new Label("Write your text:");
TextArea area = new TextArea(10, 20);
public void init() {
add(label1);
label1.setBackground(Color.orange);
add(text);
add(label2);
label2.setBackground(Color.orange);
add(area);
add(write, BorderLayout.CENTER);
write.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent z) {
WriteText writeText = new WriteText();
}
});
}
public class WriteText {
WriteText() {
try {
String str = text.getText();
if (str.equals("")) {
JOptionPane.showMessageDialog(null,
"It's not that smart... You have to enter the path and filename");
text.requestFocus();
} else {
File f = new File(str);
if (f.exists()) {
BufferedWriter out = new BufferedWriter(new FileWriter(f, true));
if (area.getText().equals("")) {
JOptionPane.showMessageDialog(null, "You haven't written anything yet!");
area.requestFocus();
} else {
out.write(area.getText());
if (f.canWrite()) {
JOptionPane.showMessageDialog(null, "There is now some text in " + str);
text.setText("");
area.setText("");
text.requestFocus();
} else {
JOptionPane.showMessageDialog(null, "There isn't any text in " + str);
}
out.close();
}
} else {
JOptionPane.showMessageDialog(null, "Error 404 File not found!");
text.setText("");
text.requestFocus();
}
}
} catch (HeadlessException | IOException x) {
}
}
}
}