简体   繁体   中英

Reading file in Java (IDE used)

I was trying to write a piece of Java code to read each line from a file and add it to an Arraylist. Here is my code:

// try catch block removed for clarity.
file = new TextFileIn("names.txt");
String line = null;
while ((line = file.readLine()) != null) {
    list.add(line);
}

names.txt was located in the same package folder as my code. The IDE I used was Eclipse. When I run the code however I got a FileNotFoundException . The TextFileIn class comes from http://www.javaranch.com/doc/com/javaranch/common/TextFileIn.html

How could I get the file to be found?

You're relying on the current working directory when accessing the file. The working directory depends on how you started the application. In Eclipse it's usually the project root folder. In commandline it's the currently opened directory. You cannot control this from inside the Java code, so this is considered a poor practice for files which are supposed to be part of the application itself.

The file is apparently in the same package as the running code, thus it's already in the classpath and then you could (and should) just get it straight from the classpath.

InputStream input = getClass().getResourceAsStream("names.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
String line = null;

while ((line = reader.readLine()) != null) {
    // ...
}

If you're calling this in static context, then replace getClass() by YourClassName.class where YourClassName is the name of the class where this code is sitting in.

See also:

It is located in the package folder.
"names.txt" is referencing to the project root. So you have to search in your source folder like "src/your.package/names.txt".

You should lern how to compile and run programs from the command line, and later, how to change the settings of your IDE, to do the same. The basic knowledge is something you can carry with you from IDE to IDE, from eclipse to netbeans, to IntelliJ... .

Even if you're running from the desktop by clicking or from an IDE, you're sitting virtually in a folder of your OS. In eclipse, it is by default your classes-dir when running the code, but can be modified in one of the run as tabs, and it is ${PROJECT}/bin or ${PROJECT}/classes, wherever your classes go. So you have to place your file there, but attention - it might get deleted if you press 'clean all' or something, so use a copy.

Instead of funny TextFileIn, why don't you use java.util.Scanner?

Scanner scanner = new Scanner ("names.txt");
while (scanner.hasNextLine ())
    String line = scanner.nextLine ();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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