简体   繁体   English

Java中的动态文件路径(写入和读取文本文件)

[英]Dynamic filepath in Java (writing and reading text files)

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"? 嗯..我想知道我应该将File(filePath)作为我的参数传递给我...我可以放一些像“.. \\ 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. 我不想对文件路径进行硬编码,因为如果我在另一台PC上打开我的项目,它肯定会改变。 How do i make sure that the filepath is as dynamic as possible? 如何确保文件路径尽可能动态? By the way, I'm using java. 顺便说一下,我正在使用java。

File teacherFile = new File(filePath);

You can references files using relative paths like ../myfile.txt . 您可以使用相对路径(如../myfile.txt引用文件。 The base of these paths will be the directory that the Java process was started in for the command line. 这些路径的基础将是为命令行启动Java进程的目录。 For Eclipse it's the root of your project, or what you've configured as the working directory under Run > Run Configurations > Arguments . 对于Eclipse,它是项目的根目录,或者您在“运行”>“运行配置”>“参数”下配置为工作目录的内容。 If you want to see what the current directory is inside of Java, here's a trick to determine it: 如果你想看看Java里面的当前目录是什么,这里有一个确定它的技巧:

File currentDir = new File("");
System.out.println(currentDir.getAbsolutePath());

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");

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是你的应用程序文件夹的路径,添加精确的目录/文件名,你就可以了

You can use ../myfile.txt However the location of this will change depending on the working directory of the application. 您可以使用../myfile.txt但是,此位置将根据应用程序的工作目录而更改。 You are better off determining the base directory of you project is and using paths relative to that. 您最好确定项目的基本目录并使用相对于此的路径。

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

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