How to change System.getProperty(“user.dir”) to project workspace

后端 未结 5 1385
深忆病人
深忆病人 2020-12-06 18:54

I try to read a .txt file line by line in my code, which I placed it just right under the /src/ directory, when I run it with test case or with static void main

5条回答
  •  Happy的楠姐
    2020-12-06 19:18

    The short answer is that you can't change a running application's current working directory in Java; see Changing the current working directory in Java?

    Setting the user.dir property won't work, because that doesn't affect the actual current directory that the OS uses when resolving pathnames for the application.

    Setting the -Duser.dir on the command line won't work either. Rather, you have to:

    • if you are launching using a script, cd to the relevant directory before running the application,
    • if you are launching using a ProcessBuilder, set the working directory using the directory(File) method, or
    • if you are using an Eclipse launcher, set the "Working Directory" in the launch configuration.

    Finally, what you are trying to do is (IMO) a bad idea:

    • Some folks write Tomcat and webapp config files on the assumption that Tomcat's current directory is the default location; e.g. $CATALINA_HOME/bin. (This is wrong ... but your hack will break it.)
    • When your application goes into production, you won't want to be referring back to some development sandbox.

    A better approach is to do something along the lines of @Eng.Fouad's answer.

提交回复
热议问题