-1

I have a JFileChooser and I want to set the directory it opens using some information stored in a .txt file (I'm using a .txt file to persist the desired location between sessions). I can get the file, read the data and set it to a string, but when I try to use that string to set the directory I want to open it doesn't work. My code is roughly something like this:

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

After stepping through this, however, the current directory is set to /Users/user.

If anyone has any ideas about what I'm doing wrong or a better way to accomplish this I'd love to hear it.

Thank you

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();
    }     

  }
});
bwoodruff1
  • 23
  • 1
  • 9
  • My guess is that something you assume is happening is not. Probably in a part of your code that you didn't post because you think the problem can't be there. I suggest you post the rest of your code. – Abra Mar 14 '19 at 18:29
  • @Abra Good idea, but code should be in the (specific) form of a [mcve]. Tip: `[mcve]` in a comment auto-expands to that text and link. OP: Please use code formatting for code and code snippets, structured documents like HTML/XML or input/output. To do that, select the text and click the `{}` button at the top of the message posting/editing form. – Andrew Thompson Mar 14 '19 at 23:25
  • Some of the formattings got messed up when I copied it over, Sorry if it's not as clean as your used to seeing. I also tried to add comments to help explain what I was doing throughout the process. It's very much cobbled together from what I could find around here and some other sources. – bwoodruff1 Mar 15 '19 at 12:23
  • *"Some of the formattings got messed up.."* Our comments were not **primarily** about 'formatting', but the code itself. It seems you have not read the links I offered. And a tip: Add @Abra (or whoever, the `@` is important) to *notify* the person of a new comment. – Andrew Thompson Mar 16 '19 at 02:52

2 Answers2

0

I think the directory passed as argument does not exist or is not accessible to the user you are logged in with judging from the javadoc of setCurrentDirectory():

If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.

Make sure all folders in the given path exist and are accessible to the logged user (on linux the 'executable' bit controls the accessibility of a directory). So if you see something like

-d x Documents

after executing

ls -l *

in a shell then the Documents directory is accessible.

Crispert
  • 1,102
  • 7
  • 13
  • After double checking my permissions for the directory are drwxr-xr-x – bwoodruff1 Mar 18 '19 at 12:26
  • You could check if the destination folder for the jFileChooser is an existing accessible directory using the expression **desiredPath.exists() && desiredPath.isDirectory() && desiredPath.canExecute()** and if that's false check all parent directories using desiredPath.getParent() until you find the first satisfying all conditions (which would be the same one used by the chooser). You might also want to watch out for symlinks https://stackoverflow.com/questions/2490351/detecting-a-symlink-in-java – Crispert Mar 19 '19 at 13:11
0

Found a better way to accomplish my goal using Preferences instead of trying to create and access files to store the location.

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

and then inside 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));
  }
});
bwoodruff1
  • 23
  • 1
  • 9