Java - Getting file from same package

前端 未结 4 1565
甜味超标
甜味超标 2021-01-11 13:16

If I want to read from \"Words.txt\" which is in the same package as the class, how would I do this? Doing simply Scanner = new Scanner(new File(\"Words.txt\"));

相关标签:
4条回答
  • 2021-01-11 13:34
    Scanner = new Scanner(new File("/path/to/Words.txt")); 
    

    The argument in the File() constructor, Is the path relative to the system your VM is running on, it s doesn't depend on the classe's package.

    If you your words.txt is a resource packaged with your war you can see here : Load resource from anywhere in classpath

    0 讨论(0)
  • 2021-01-11 13:35
    Scanner scanner = new Scanner(getClass().getResourceAsInputStream("Words.txt"));
    
    String s = new String();
    
    while(scanner.hasNextLine()){
    
    
            s = s + scanner.nextLine();
    
    
     }
    
    0 讨论(0)
  • 2021-01-11 13:39
    InputStream is = MyClass.class.getResourceAsStream("Words.txt");
    ...
    
    0 讨论(0)
  • 2021-01-11 13:43

    Assuming the text file is in the same directory as the .class, rather than the .java file you can do

    Scanner scanner = new Scanner(getClass().getResourceAsStream("Words.txt"));
    

    What you have will look for the file in the current working directory. When you are building your program this is typically the root directory of your program. When you run it as a standalone program it is usually the directory the program was started from.

    0 讨论(0)
提交回复
热议问题