简体   繁体   English

在Java中将相对路径写入文本文件

[英]writing a relative path to a text file in java

I'm working on this project, and I am accessing a lot of text files that I have put in a resources folder. 我正在从事这个项目,我正在访问放置在资源文件夹中的许多文本文件。 I'm having a lot of trouble writing the relative path to these files. 将相对路径写入这些文件时遇到很多麻烦。 In the command line, I got from the directory containing the java file with a main method to the text file I want with "cd ../../../../../../../resources/Information/ConfluneceTotalLists/table.txt". 在命令行中,我从包含带有main方法的java文件的目录到我想要的文本文件,其中包含“ cd ../../../../../../../resources/ Information / ConfluneceTotalLists / table.txt”。 I tried writing using this in the main method to get the file, but it did not work. 我尝试在main方法中使用此方法编写文件,但没有用。 How can I fix this? 我怎样才能解决这个问题? Also, when a java program is running, is the current directory the one containing the java file with the main method? 另外,当Java程序运行时,当前目录是否是包含带有main方法的java文件的目录?

Use: 采用:

System.out.println(System.getProperty("user.dir")));

To find out what the directory your Java program is running from. 找出您的Java程序从哪个目录运行。 Then use relative paths from this location. 然后使用此位置的相对路径。

When a java program runs, it inherits the working directory of the program that launched it. Java程序运行时,它将继承启动它的程序的工作目录。 This has nothing to do with the Java source file or class file of the main class. 这与主类的Java源文件或类文件无关。

cd is a unix shell command, in java it is sufficient to specify the full path (relative or absolute) when you open the file. cd是unix shell命令,在Java中,打开文件时指定完整路径(相对或绝对)就足够了。 As for the current directory, it is usually the one you run the program from. 至于当前目录,通常是您从中运行程序的目录。 In case you're using an IDE, it would usually be the main project folder. 如果您使用的是IDE,它通常是主项目文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM