Java, reading a file from current directory?

前端 未结 7 745
自闭症患者
自闭症患者 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:05

    Try

    System.getProperty("user.dir")
    

    It returns the current working directory.

    0 讨论(0)
  • 2020-12-02 07:09

    Try this:

    BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
    
    0 讨论(0)
  • 2020-12-02 07:11

    Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in

    ----src
    --------package1
    ------------myfile.txt
    ------------Prog.java
    

    you can specify its path as "src/package1/myfile.txt" from Prog.java

    0 讨论(0)
  • 2020-12-02 07:14

    try using "." E.g.

    File currentDirectory = new File(".");
    

    This worked for me

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-12-02 07:24

    None of the above answer works for me. Here is what works for me.

    Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:

    URL path = Foo.class.getResource("myFile.txt");
    File f = new File(path.getFile());
    reader = new BufferedReader(new FileReader(f));
    
    0 讨论(0)
提交回复
热议问题