how to get a conf.txt path in eclipse

蹲街弑〆低调 提交于 2019-12-25 11:34:06

问题


I have an eclipse project and in one folder there is a text file "conf.txt". I can read and write the file when I use the path on my Computer. But I have to write my own folders there as well, not only the workspace folders. So know I want to commit the program for others, but then the path I put in the program won't work, because the program is running on a different computer. What I need is to be able to use the file with only the path in my workspace.

If I just put in the path, which is in the workspace it won't work.

This is how my class File looks like.

public class FileUtil {

public String readTextFile(String fileName) {

      String returnValue = "";
      FileReader file = null;

      try {
        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);
        String line = "";
        while ((line = reader.readLine()) != null) {
          returnValue += line + "\n";
        }
        reader.close();
      } catch (Exception e) {
          throw new RuntimeException(e);
      } finally {
        if (file != null) {
          try {
            file.close();
          } catch (IOException e) {
            // Ignore issues during closing 
          }
        }
      }
      return returnValue;
    }

public void writeTextFile(String fileName, String s) throws IOException {

    BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
    try {
        output.write(s);
    }
      finally {
        output.close();
      }
  }

}

I hope someone knows what to do.

Thanks!


回答1:


I am not sure but I attached the screen shot with little bit explanation. Let me know if you have any question.

Your project is root folder here and images as resources folder from where you can access the file using relative path.

// looks for file in root --> file.txt
scan = new Scanner((new File("file.txt")));

// looks for file in given relative path i.e. root--> images--> file.txt
scan = new Scanner((new File("images/file.txt"))); 




回答2:


If you want your configuration file to be accessed through a relative path, you shouldn't need to add anything to the front of it. Assuming you're using a bufferedReader, or something of the sort it would look as simple as: br = new BufferedReader(new FileReader("config.txt"));

This will cause a search of the runtime directory, making it so you don't have to fully qualify the path to your file. That being said you have to ensure your config.txt is within the same directory as your executable.



来源:https://stackoverflow.com/questions/17307817/how-to-get-a-conf-txt-path-in-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!