开发者

placing a input file relative to program

In my program (simple plain cosole app) I开发者_运维百科 am reading a file a.txt. Now I will be giving the program to someone else and he should be able to run it. I don't want the file path to be fixed like D:\a.txt , instead it should be relative to my program. Where should I place the file so that my program always finds it?

File file = new File("D:\aks.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while( (str= bufferedReader.readLine())!=null){

}

My code is working fine when I hard code the path like D:\a.txt


Put the file in the classpath (e.g. the package root or in a certain package) and just get it straight from the classpath as follows

InputStream input = getClass().getResourceAsStream("/a.txt");
// ... (continue with InputStreamReader and so on)

(the exact path depends on the location of the current class and whether you prefix with / to start from package root and which classloader you're using)

Package and distribute it as a single executabele JAR file.

See also:

  • Java: Pathnames not working once I export to JAR
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜