簡體   English   中英

運行Java命令應用程序時無法從文件讀取

[英]having trouble reading from file when running a java command app

我想制作一個簡單的命令行Java應用程序,該應用程序將與該應用程序的jar文件位於同一目錄中的文件的名稱作為參數,以便我可以從中讀取。 但是我得到了FileNotFoundException。 這是我的代碼:

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]);
        }
    }
}

因此,假設我在同一目錄中有一個名為a.txt的txt文件和myApp.jar文件。 我將cmd和cd啟動到此特定目錄,然后鍵入:

java -jar myApp.jar a.txt

我得到“找不到文件a.txt”

我究竟做錯了什么?

編輯:考慮之后,我猜找不到文件,因為它應該與類文件位於同一目錄中,換句話說,在jar中。 所以我的問題是,當它在jar文件之外時如何訪問它?

啟動應用程序時,“當前”目錄將由環境確定。 要找出它在哪里,請將錯誤輸出行更改為:

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

(您可能必須在main()聲明中添加throws IOException才能編譯以上內容)。

如果要訪問類路徑(或jar)中的資源,請使用ClassLoader.getResourceAsStream-然后,將使用InputStreamReader將Reader包裹在返回的InputStream周圍。

檢查一下...(找到的內容)

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]);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM