Java, reading a file from current directory?

前端 未结 7 776
自闭症患者
自闭症患者 2020-12-02 06:37

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).

In other words, if the user

7条回答
  •  爱一瞬间的悲伤
    2020-12-02 07:20

    If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:

    URL path = ClassLoader.getSystemResource("myFile.txt");
    if(path==null) {
         //The file was not found, insert error handling here
    }
    File f = new File(path.toURI());
    
    reader = new BufferedReader(new FileReader(f));
    

提交回复
热议问题