-3

I would like to import a file path in Java. Since the path can change, I want it to be outside of the code and so it is changeable. I have read that that can solve with an INI file. Well, I've tried it. I have the following Java code:

import java.util.*;
import java.io.*;

class readIni {
public static void main(String args[]) {
readIni ini = new readIni();
ini.doit();
}
public void doit() {
try{
  Properties p = new Properties();
  p.load(new FileInputStream("user.ini"));
  p.list(System.out);
  }
catch (Exception e) {
  System.out.println(e);
  }
}

}

My Ini-file:

file = H:/

Now, the console shows exactly the Ini-file and not the contents of the directory....What is wrong?

LostInTranslate
  • 93
  • 1
  • 2
  • 11
  • 1
    Why should it write anything else? – Maurice Perry Jul 31 '17 at 13:02
  • It should shown the files in the pathfiles. Sry, but i don´t understand what you mean. Whats wrong with the code above? – LostInTranslate Jul 31 '17 at 13:15
  • The `ini` file should not show the files in the path. It should hold the path that contains the files you want to show. Once you have the path, you can use an answer from [here](https://stackoverflow.com/questions/15482423/how-to-list-the-files-in-current-directory) to show the files in that folder. – SedJ601 Jul 31 '17 at 13:50
  • Oh okay, but why shows my java Code the content of the ini-file? Isn't the ini-file correct? – LostInTranslate Jul 31 '17 at 14:03

1 Answers1

0

If you want to just save a file path, consider using the following code:

File file = new File("H:\whatever.txt");

// Write to the file
FileWriter fw = new FileWriter(file);
fw.write("your path goes here");
fw.close();

// Read from the file
BufferedReader br = new BufferedReader(new FileReader(file));
String path = br.readLine();
br.close();
eliaspr
  • 302
  • 3
  • 15
  • The file path is changing and i don´t want to change the code, only the ini-file. So I think your solution is not very portable. – LostInTranslate Jul 31 '17 at 13:14
  • Yeah, you just change the contents of the `H:\whatever.txt` file. There is no `.ini` file in my example, just a simple text file containing a file path. – eliaspr Jul 31 '17 at 18:35
  • Oh okay, it works. But now I have the problem with saving the txt. I have no idea where it will save at the end. But I have to write a path in the code....any ideas where I can save it and txt is always on the same path?? Also at another computer? – LostInTranslate Aug 01 '17 at 07:42
  • The path you write in the code is where the txt file is being saved to or loaded from. And you could consider using `System.getenv("APPDATA")` to get the path to the users %appdata% folder. – eliaspr Aug 01 '17 at 07:45