[英]Where do I put the txt file that I want to read in Java?
If I am building an application in Eclipse using Java, and I want this application to read from a txt file, where should I put the txt file in the package in order to not have to specify its path (so that I can just say "file.txt").如果我正在使用 Java 在 Eclipse 中构建一个应用程序,并且我希望这个应用程序从一个 txt 文件中读取,我应该将 txt 文件放在包中的什么位置以便不必指定其路径(这样我就可以说“文件.txt”)。 I thought that it was supposed to go in the src folder, but it's not working.
我认为它应该放在 src 文件夹中,但它不起作用。
Right click the project folder and click New -> file.右键单击项目文件夹,然后单击新建 -> 文件。 The file will be in the Project folder and not in the source folder.
该文件将在项目文件夹中,而不是在源文件夹中。
Put the file in the folder from where you run your Java application (your current/working folder).将文件放在运行 Java 应用程序的文件夹(当前/工作文件夹)中。 If you're using the default settings of Eclipse to run your application, you should put the file directly inside the Eclipse project folder.
如果您使用 Eclipse 的默认设置来运行您的应用程序,您应该将该文件直接放在 Eclipse 项目文件夹中。 To create the file in the Eclipse project, you can simply drag-and-drop it there or right-click on the Eclipse project and create a new file.
要在 Eclipse 项目中创建文件,您可以简单地将它拖放到那里或右键单击 Eclipse 项目并创建一个新文件。
If you don't want to specify a path, and want to open a File from the file system using the java.io.File API, then put it in the working directory.如果您不想指定路径,并且想使用 java.io.File API 从文件系统打开一个 File,则将其放在工作目录中。
In Eclipse, the working directory defaults to the root level of your project, but you can modify it (and also review what it is set to) in an Eclipse Run Configuration.在 Eclipse 中,工作目录默认为项目的根级别,但您可以在 Eclipse 运行配置中修改它(并查看它的设置)。 They are accessible under the "Run > Run Configurations..." menu option, and the working directory setting is under the "Arguments" tab for Java programs.
它们可以在“运行 > 运行配置...”菜单选项下访问,工作目录设置在 Java 程序的“参数”选项卡下。
The important thing is for the directory containing your file to be on the classpath.重要的是包含您的文件的目录位于类路径上。 When you're using Eclipse's run dialog for the settings of your project, there's a tab for classpath.
当您使用 Eclipse 的运行对话框进行项目设置时,有一个用于类路径的选项卡。 You can use it learn what's already on the classpath, and to make additions if you want to.
您可以使用它来了解类路径中已有的内容,并根据需要进行添加。
As mentioned above by @tschaible, the Eclipse working directory defaults to the root of the project.正如@tschaible 上面提到的,Eclipse 工作目录默认为项目的根目录。 Therefore, the program will look for the file from the root level.
因此,程序将从根级别查找文件。
However, if you intend to run the program from the command line, it acts differently because the working directory defaults to the folder that you are running the java file from (aka the src folder).但是,如果您打算从命令行运行程序,它的行为会有所不同,因为工作目录默认为您从中运行 java 文件的文件夹(也称为 src 文件夹)。 Therefore, it is important to keep this discrepancy in mind when testing your java program from the command line.
因此,在从命令行测试 Java 程序时,务必牢记这种差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.