JFileChooser.SetCurrentDirectory 不工作

JFileChooser.SetCurrentDirectory not working

我有一个 JFileChooser,我想使用存储在 .txt 文件中的一些信息来设置它打开的目录(我使用 .txt 文件在会话之间保留所需的位置)。我可以获取文件、读取数据并将其设置为字符串,但是当我尝试使用该字符串设置我想要打开的目录时,它不起作用。我的代码大致是这样的:

//buffer contains a byte[] for "/Users/user/Documents/Work/folderToOpen" desiredPath = new String(buffer); jFileChooser1.setCurrentDirectory(new java.io.File(desiredPath));

然而,在逐步执行此操作后,当前目录设置为 /Users/user。

如果有人对我做错了什么有任何想法或更好的方法来实现这一点,我很乐意听到。

谢谢

private static String LAST_FOLDER_USED = null;

//Get the desired file path for user preferences
String pluginRoot = System.getProperty("user.dir") + File.separator.toString();
//Create a file using the desired file Path
File userPreferences = new File(pluginRoot + File.separator + "UserPreferences.txt");

//Get a file called UserPreferences.txt from target/classes to create an input stream
String fileName = "UserPreferences.txt";
InputStream readInFile = getClass().getResourceAsStream(fileName);{

//Convert input stream to read from the desired file in the plug-in root ("filePath" Created Above)
  try{
    readInFile = new FileInputStream(userPreferences);
  }
  catch (IOException e){
    e.printStackTrace();
  }}

//Read the readInFile into a byte[]
String desiredPathToOpenImage;
byte[] buffer = new byte[1000];

int i = 0;{
try {
  while((i = readInFile.read(buffer)) !=-1){
        System.out.println(new String(buffer));
        i++;
}} 
catch (IOException e) {
    e.printStackTrace();
};
//Convert byte[] to string (This should be the path to the desired folder when selecting an image)
desiredPathToOpenImage = new String(buffer);
}

//Create a New File using the desired path
File desiredPath = new File(desiredPathToOpenImage + File.separator + "prefs.txt");

public SelectImage(Viewer parent, boolean modal) {
  super(parent, modal);
  initComponents();
  int returnVal = jFileChooser1.showOpenDialog(parent);
 // Sets up arrays for storing file information to be passed back to the viewer class.
  String[] filePath = new String[jFileChooser1.getSelectedFiles().length];
  String[] fileName = new String[jFileChooser1.getSelectedFiles().length];
  String[] fileDir = new String[jFileChooser1.getSelectedFiles().length];
  if (returnVal == JFileChooser.APPROVE_OPTION) {
   // Cycles through the selected files and stores each piece accordingly
   for (int i = 0; i < jFileChooser1.getSelectedFiles().length; i++) {
    File file = jFileChooser1.getSelectedFiles()[i];
    filePath[i] = file.getPath();
    fileName[i] = file.getName();
    fileDir[i] = file.getParent();
  }

 }
 parent.setFilePath(filePath, fileName, fileDir);

}

private void initComponents() {

 jFileChooser1 = new javax.swing.JFileChooser();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jFileChooser1.setMultiSelectionEnabled(true);
      //Checks folder_Path to see if a value is present. If value is present sets jFileChooser Directory to that value
        if(desiredPathToOpenImage.contains(File.separator)){
            //Create a File using the desired path for selecting images
       //****Currently doesn't set the Directory correctly****//
            jFileChooser1.setCurrentDirectory(desiredPath);
        }
      //If no value is present in LAST_FOLDER_USED sets jFileChooser Directory to desktop
        else{
            jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
        }
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
  public void actionPerformed(java.awt.event.ActionEvent evt) {
    jFileChooser1ActionPerformed(evt);

//After file is selected sets value of LAST_FOLDER_USED to the absolute path of that file
    LAST_FOLDER_USED = jFileChooser1.getCurrentDirectory().toString() + File.separator + "UserPreferences.txt";        

    try {
        FileWriter fileWriter = new FileWriter(userPreferences);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        bufferedWriter.write(jFileChooser1.getCurrentDirectory().toString());
        OutputStream outPut = new FileOutputStream(pluginRoot +    File.separator + "UserPreferences.txt");
        outPut.write(LAST_FOLDER_USED.getBytes());
        outPut.close();

        bufferedWriter.close();
    } catch (IOException e) {
        System.out.println("Error Writing to File" + desiredPathToOpenImage);
        e.printStackTrace();
    }     

  }
});

根据 setCurrentDirectory() 的 javadoc 判断,我认为作为参数传递的目录不存在或您登录的用户无法访问:

如果作为 currentDirectory 传入的文件不是目录,则文件的父级将用作 currentDirectory。如果父级不可遍历,那么它将沿着父级树向上遍历,直到找到一个可遍历的目录,或者到达文件系统的根。

确保给定路径中的所有文件夹都存在并且登录用户可以访问(在 linux 上,'executable' 位控制目录的可访问性)。所以如果你看到类似

-d x 文件

执行后

ls -l *

在 shell 中可以访问 Documents 目录。

找到了一种更好的方法来实现我的目标,使用 Preferences 而不是尝试创建和访问文件来存储位置。

Preferences prefs = Preferences.userNodeForPackage(this.getClass());
static String LAST_FOLDER_USED = "LAST_FOLDER_USED";
String folder_Location;

然后在 initComponents()

 if(LAST_FOLDER_USED != null){
            jFileChooser1.setCurrentDirectory(new File(prefs.get(LAST_FOLDER_USED, LAST_FOLDER_USED)));
        }
        else{
            jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
        }
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
  public void actionPerformed(java.awt.event.ActionEvent evt) {
    jFileChooser1ActionPerformed(evt);

    folder_Location = jFileChooser1.getCurrentDirectory().toString();
    prefs.put(LAST_FOLDER_USED, folder_Location);
    //System.out.println(prefs.get(LAST_FOLDER_USED, folder_Location));
  }
});