iT邦幫忙

1

Apache NetBeans IDE 10.0用 FileReader要讀取的檔案名稱(路徑)讀不到

Tzu 2020-09-26 10:15:311123 瀏覽

https://ithelp.ithome.com.tw/upload/images/20200926/20119035p3l8PbnOnm.png
https://ithelp.ithome.com.tw/upload/images/20200926/20119035AM6NgwAe4Z.png

程式碼:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author User
 */
public class ReadTxtFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        System.out.println("要讀取的檔案名稱(路徑)");
        System.out.print("->");
        
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String str=br.readLine();
        FileReader fr=new FileReader(str);
        
        System.out.println("\n以下是文字檔"+str+"的內容:");
        int ch;
        while((ch=fr.read())!=-1)
            System.out.print((char)ch);
        
        fr.close();
    }
    
}


應該是要改程式碼..但是??
謝謝各位大大


解答:
就是要打絕對路徑~如果像我一樣容易迷路的人 可以加入 System.out.println(System.getProperty("user.dir"));
這句找到絕對路徑在哪裡(我這裡txt檔因為已經跟JAVA檔放在一起..所以基本上會在同一個地方)

https://ithelp.ithome.com.tw/upload/images/20200926/20119035NDphbICao4.pnghttps://ithelp.ithome.com.tw/upload/images/20200926/201190352EErOppalH.png

還不會就先不要隨便亂教人。
你的理解還是有小問題。

除了絕對路徑跟相對路徑你還得了解。還得知道檔案對應路徑跟程式運行路徑。
這些都是基本的東西。要再多學習。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

3
海綿寶寶
iT邦大神 1 級 ‧ 2020-09-26 10:51:14
最佳解答

根據這篇的答案

在一開始加一列System.out.println(System.getProperty("user.dir"));
看一下目前目錄是那裡

再把 ILOVEJAVA.txt 搬到那裡去試看看

另外,點這裡是我這次鐵人賽唯一的一篇文章,喜歡的話左上角點 Like

Tzu iT邦新手 1 級 ‧ 2020-09-26 18:40:48 檢舉

謝謝 我等等更新在樓上

1

真不知道是在「但是」什麼~~~有做其它的努力嘛?
這樣的問題找一下就知道了吧。

還有啊,你不要再將編輯器當標題來問了
java就java。搞的好像很複雜

Tzu iT邦新手 1 級 ‧ 2020-09-26 18:41:12 檢舉

謝謝 我等等發文用JAVA

我要發表回答

立即登入回答