简体   繁体   English

如何从java中的任何目录和对话框读取文本文件?

[英]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.我正在创建一个游戏和关卡编辑器,其中关卡存储在 .txt 文件中。 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!感谢您的帮助!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM