简体   繁体   中英

having trouble reading from file when running a java command app

i want to make a simple command line java app that gets as argument the name of a file located in the same directory with the jar file of the app, so that i can read from it. however i'm getting a FileNotFoundException. here's my code:

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("Give the name of the input file as argument.");
    } else if (args.length > 1) {
        System.out.println("Only one input file is allowed");
    } else {
        try {
            BufferedReader in = new BufferedReader(new FileReader(args[0]));
            System.out.println("File found");
        } catch (FileNotFoundException e) {
            System.out.println("Could not find file " + args[0]);
        }
    }
}

so suppose i'm having a txt file named a.txt and myApp.jar file inside the same directory. i start cmd and cd to this specific directory, and then type:

java -jar myApp.jar a.txt

and i get "Could not find file a.txt"

what am i doing wrong?

EDIT: after thinking of it i guess the file is not found because it should be in the same directory with the class file, in other words inside the jar. so my question is, how is it possible to access it when it is outside of the jar file?

The "current" directory is going to be determined by the environment when you launch your application. To find out where it's looking, change the error output line to be:

System.out.println("Could not find file " + (new File(args[0])).getCanonicalPath());

(you may have to add throws IOException to your main() declaration to get the above to compile).

If you want to access resources inside the classpath (or jar), use ClassLoader.getResourceAsStream - you will then wrap a Reader around the returned InputStream using InputStreamReader .

Check with this... (what you find)

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        System.out.println("Give the name of the input file as argument.");
    } else if (args.length > 1) {
        System.out.println("Only one input file is allowed");
    } else {
        try {
            BufferedReader in = new BufferedReader(new FileReader(args[0]));
            System.out.println("File found");
        } catch (FileNotFoundException e) {
            // Finding the dir
            String current = new java.io.File( "." ).getCanonicalPath();
            System.out.println("Current dir: " + current);
            System.out.println("Current user.dir: " + System.getProperty("user.dir"));
            //
            System.out.println("Could not find file " + args[0]);
        }
    }
}

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