我正在用 Java(IDE:NetBeans 7.4、JDK 7、Swing API)编写一个程序来替代微软糟糕的记事本。
我面临的问题是,我添加了一个按钮来获取用户希望保存文件的目录。这是按钮的代码(命名为choosedir):
private void choosedirActionPerformed(java.awt.event.ActionEvent evt) {
int select=choose.showOpenDialog(this);
if (select == choose.APPROVE_OPTION){
String dir=choose.getName(choose.getCurrentDirectory());
directory.setText(dir.toString()+"-");
}
}
上面的代码在文本框“目录”中设置选择的目录。
现在,作者的代码:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String dir=choose.getName(choose.getCurrentDirectory());
directory.setText(dir.toString());
File file=new File(dir+name+".txt");
try{
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
out.append(input.getText());
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
问题是: 1. 没有文件被保存 2. 无论我选择什么目录,它都会显示在 Windows 资源管理器中看到的目录名称。就像,如果我想要它在 C:/Windows/Temp 中,它只显示 Temp。甚至对于 C:/,它显示“本地磁盘 C:.
2013 年 11 月 16 日更新:尽管得到了 alex 的帮助,但该程序仍然无法运行。这是整个源代码:
import java.io.*;
public class QuickPad_v1 extends javax.swing.JFrame {
/**
* Creates new form QuickPad_v1
*/
public QuickPad_v1() {
initComponents();
}
/* Avoid the non-programmed buttons below! */
private void extensionActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String dir=directory.getText();
File file=new File("C://"+name+".txt");
try{
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
out.append(input.getText());
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
private void choosedirActionPerformed(java.awt.event.ActionEvent evt) {
int select=choose.showOpenDialog(this);
if (select==choose.APPROVE_OPTION){
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new QuickPad_v1().setVisible(true);
}
});
}
请需要帮助!我给你一票,保证!