Java文件目录问题
我正在开发一个java程序,它接受一个学生的名字,并在JTextPane上显示名字和日期。当用户按下exit键时,程序应自动将文件保存在指定目录中的新文件夹中,该文件夹与用户为学生提供的文件夹同名。下面是我的代码:Java文件目录问题,java,file,file-io,directory,jtextpane,Java,File,File Io,Directory,Jtextpane,我正在开发一个java程序,它接受一个学生的名字,并在JTextPane上显示名字和日期。当用户按下exit键时,程序应自动将文件保存在指定目录中的新文件夹中,该文件夹与用户为学生提供的文件夹同名。下面是我的代码: public class StudentRecorder extends JFrame implements ActionListener{ MyKeyListener listener; public JTextPane page; private JScrollPane scr
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();
}
}
}
}
我在程序中遇到一个问题,文件没有保存到提供名称的目录中。它始终会在控制台“未创建目录”中弹出。谁能告诉我如何解决这个问题?我的代码中没有其他错误阻止它运行
提前感谢所有回复者。您遇到此问题的原因是您试图在./Desktop中创建目录,而您是从没有桌面文件夹的文档中运行此目录的。要将其保存到桌面,必须使用绝对路径。绝对路径在unix mac和linux上以a/开头,在Windows上以C:开头:
File f = new File("/Users/yourname/Desktop/" + name);
运行此程序的目录是什么?它嵌套在“我的文档”文件夹中。我希望将我的目录保存在Java项目文件夹中,但它一直在给我save‘directory Not Created’语句。