将JFileChooser设置为打开当前目录

Tof*_*fiq 8 java swing jfilechooser file

我创建了一个JFileChooser来打开一个文件,但是当我选择一个文件然后打开它时,第二次我要选择一个文件时,JFileChooser不在当前目录中.如何设置JFileChooser打开当前目录?

JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
         fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
         int result = fileChooser.showOpenDialog( this );
         if ( result == JFileChooser.APPROVE_OPTION ){
              File fileName = fileChooser.getSelectedFile();
              File path=fileChooser.getCurrentDirectory();
              if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
              {
                 JOptionPane.showMessageDialog( this, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE );
              }
              else{
               currentPath=path.getPath()+"\\"+fileName.getName();}
             } 
Run Code Online (Sandbox Code Playgroud)

jef*_*unt 12

通过参数(也可以是目录,FYI)将目录传递给构造函数,或者在使JFileChooser可见之前使用该方法.FileFile.setCurrentDirectory(File dir)

此外,要使JFileChooser保持在同一文件夹中,您需要保存上次选择的文件/目录的文件夹,并使用THAT值来控制它在随后的时间内启动的文件夹 .setCurrentDirectory(File dir)