Java文件目录问题

时间:2014-07-27 23:43:22

标签: java file file-io directory jtextpane

我正在开发一个java程序,它接受学生姓名并在JTextPane上显示名称和日期。当用户按下退出时,程序应该自动将文件保存在新目录中的指定目录中,该新文件夹的名称与用户为学生提供的名称相同。以下是我的代码:

public class StudentRecorder extends JFrame implements ActionListener{

MyKeyListener listener;
public JTextPane page;
private JScrollPane scroll;
private JMenuBar menubar;
private AttributeSet aset;
public String name; 

private JMenu menufile;
private JMenuItem exit;

StudentRecorder(){
    super("Student Recorder");
    init();

    this.setSize(400, 400); 
    this.setLocation(400, 400);
    this.setVisible(true);
}

void init(){
    menubar = new JMenuBar();
    name = JOptionPane.showInputDialog(this, "Enter Student's Name:\n(For locations of files to be preserved, "
            + "names\nare case-sensitive.)", "Student Name", JOptionPane.QUESTION_MESSAGE);
    String timeStamp = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(Calendar.getInstance().getTime());        
    page = new JTextPane();

    if (name.equals("")){
        aset = StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
        page.setCharacterAttributes(aset, false);
        page.setText(timeStamp + "\n" + "(Student Name Not Typed In.  You must manually save this file.  File "
                + "wont be autosaved.)" + "\n\n");
    }
    else{
        page.setText(timeStamp + "\n" + name + "\n\n");
    }

    //Declaration
    menufile = new JMenu("File");
    exit = new JMenuItem("Exit");

    //Adding to JMenuBar
    menubar.add(menufile);
    menufile.add(exit);

    //Add ActionListener
    exit.addActionListener(this);

    //Page characteristics
    aset = StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLACK);
    page.setCharacterAttributes(aset, false);
    Font font = new Font("Arial", Font.PLAIN, 14);          
    page.setFont(font);
    this.setJMenuBar(menubar);
    scroll = new JScrollPane(page);
    this.add(scroll);
    scroll.createHorizontalScrollBar();     
    listener = new MyKeyListener();
    page.addKeyListener(listener);
    page.setFocusable(true);
}

@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource() == exit){
        File f = new File("./Desktop/" + name);
        try{
            if(f.mkdir()){
                System.out.println("Directory Created.");
                System.exit(0);
            }
            else{
                System.out.println("Directory Not Created.");
            }
        }catch(Exception e1){
            e1.printStackTrace();
        }

    }

}

}

我在我的程序中遇到了一个问题,即文件没有保存到提供名称的目录中。它一直弹出控制台'目录未创建'。任何人都可以告诉我如何解决这个问题?我的代码中没有其他错误阻止它运行。

感谢所有回复的人。

1 个答案:

答案 0 :(得分:0)

您遇到此问题的原因是您尝试在./Desktop内创建一个目录,而您正在Documents内部运行此目录,而该目录中没有Desktop文件夹。要将其保存到桌面,您必须使用绝对路径。绝对路径以unix(mac和linux)上的/和Windows上的C:开头:

File f = new File("/Users/yourname/Desktop/" + name);