Java 中的动态文件路径(写入和读取文本文件)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5579092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic filepath in Java (writing and reading text files)
提问by Alistair_dumb
Okay, so I want to read a file name myfile.txt and let's say I'll be saving it under this directory:
好的,所以我想读取一个名为 myfile.txt 的文件,假设我将把它保存在这个目录下:
home/myName/Documents/workspace/myProject/files myfile.txt
home/myName/Documents/workspace/myProject/files myfile.txt
hmmm.. I want to know what I should pass on the File(filePath)
as my parameter... Can I put something like "..\myfile.txt"? I don't want to hard code the file path, because, it will definitely change if say I open my project on another PC. How do i make sure that the filepath is as dynamic as possible? By the way, I'm using java.
嗯..我想知道我应该传递什么File(filePath)
作为我的参数......我可以放一些像“..\myfile.txt”这样的东西吗?我不想对文件路径进行硬编码,因为如果说我在另一台 PC 上打开我的项目,它肯定会改变。我如何确保文件路径尽可能动态?顺便说一句,我正在使用java。
File teacherFile = new File(filePath);
回答by WhiteFang34
You can references files using relative paths like ../myfile.txt
. The base of these paths will be the directory that the Java process was started in for the command line. For Eclipse it's the root of your project, or what you've configured as the working directory under Run > Run Configurations > Arguments. If you want to see what the current directory is inside of Java, here's a trick to determine it:
您可以使用相对路径(如../myfile.txt
. 这些路径的基础将是 Java 进程在命令行中启动的目录。对于 Eclipse,它是您项目的根目录,或者您在Run > Run Configurations > Arguments下配置为工作目录的目录。如果您想查看 Java 中当前目录的内容,可以使用以下技巧来确定它:
File currentDir = new File("");
System.out.println(currentDir.getAbsolutePath());
回答by vbence
You can use relative paths, by default they will be relative to the current directory where you are executing the Java app from.
您可以使用相对路径,默认情况下它们将相对于您从中执行 Java 应用程序的当前目录。
But you can also get the user's home directory with:
但是您也可以通过以下方式获取用户的主目录:
String userHome = System.getProperty("user.home");
回答by MByD
You can do it:
你能行的:
File currentDir = new File (".");
String basePath = currentDir.getCanonicalPath();
now basePath
is the path to your application folder, add it the exact dir / filename and you're good to go
现在basePath
是您的应用程序文件夹的路径,将其添加为确切的目录/文件名,您就可以开始了
回答by Peter Lawrey
You can use ../myfile.txt
However the location of this will change depending on the working directory of the application. You are better off determining the base directory of you project is and using paths relative to that.
您可以使用../myfile.txt
但是,它的位置将根据应用程序的工作目录而变化。您最好确定项目的基本目录并使用相对于该目录的路径。