Search code examples
javafileclasspathinputstreamfileinputstream

How to read a text file from any directory and dialog in java?


I'm creating a game and level editor where levels are stored in .txt files. On opening, the app opens a dialog to choose a file. This works perfectly except it can't read files from outside the classpath. What is a simple way to make it able to read a file from outside the classpath?

For getting the file I use:

public void getLevelPath() {
    FileDialog dialog = new FileDialog((Frame) null, "Select File to Open");
    dialog.setDirectory("C://");
    dialog.setMode(FileDialog.LOAD);
    dialog.setVisible(true);
    String file = dialog.getFile();
    System.out.println(file + " chosen.");
    levelPath = file;
}

And for reading I use:

    InputStream is = this.getClass().getResourceAsStream(path);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

Thank you for your help!


Solution

  • File inputFile = new File(path);
    InputStream is = new FileInputStream(inputFile );
    BufferedReader br = new BufferedReader(new InputStreamReader(is));