user1212818
user1212818

Reputation:

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"). I thought that it was supposed to go in the src folder, but it's not working.

Upvotes: 17

Views: 119933

Answers (6)

Ian Fernandes
Ian Fernandes

Reputation: 76

As mentioned above by @tschaible, the Eclipse working directory defaults to the root of the project. 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). Therefore, it is important to keep this discrepancy in mind when testing your java program from the command line.

Upvotes: 1

Hackster
Hackster

Reputation: 284

Right click the project folder and click New -> file. The file will be in the Project folder and not in the source folder.

Upvotes: 21

case
case

Reputation: 124

The way this can be done is using .getResourceAsStream("file.txt")

SO thread

Downvoted for a correct answer? Wierd...

Upvotes: 3

user888379
user888379

Reputation: 1477

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. You can use it learn what's already on the classpath, and to make additions if you want to.

Upvotes: 1

tschaible
tschaible

Reputation: 7695

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.

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. They are accessible under the "Run > Run Configurations..." menu option, and the working directory setting is under the "Arguments" tab for Java programs.

Upvotes: 1

reprogrammer
reprogrammer

Reputation: 14728

Put the file in the folder from where you run your Java application (your current/working folder). If you're using the default settings of Eclipse to run your application, you should put the file directly inside the Eclipse project folder. 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.

Upvotes: 5

Related Questions