JFileChooser.SetCurrentDirectory无法正常工作

时间:2019-03-14 17:59:23

标签: java swing jfilechooser

我有一个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();
    }     

  }
});

2 个答案:

答案 0 :(得分:0)

我认为以参数形式传递的目录不存在,或者从setCurrentDirectory()的javadoc判断,登录的用户无法访问该目录:

如果作为currentDirectory传入的文件不是目录,则该文件的父级将用作currentDirectory。如果父级不可遍历,则它将沿父级树行进直到找到可遍历目录或命中文件系统的根。

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

-d x文档

执行后

<CheckBox
  label='I accept the Terms and Conditions'
  value={this.state.checked}
  onValueChange={() => this.setState({ checked: !this.state.checked })}
/>

在外壳中,然后可以访问Documents目录。

答案 1 :(得分:0)

找到了一种更好的方法来使用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));
  }
});