17

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.

6 Answers6

21

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

Hackster
  • 284
  • 2
  • 7
5

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.

reprogrammer
  • 14,298
  • 16
  • 57
  • 93
3

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

SO thread

Downvoted for a correct answer? Wierd...

Community
  • 1
  • 1
case
  • 124
  • 4
1

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.

tschaible
  • 7,635
  • 1
  • 31
  • 34
1

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.

user888379
  • 1,343
  • 12
  • 30
1

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.