Read file from a folder inside the project directory

醉酒当歌 提交于 2019-12-01 10:57:01

Use

File file = request.getServletContext().getRealPath("/files/BB.key");

This translates URL paths relative (hence '/') from the web contents directory to a file system File.

For a portable web application, and knowing the file is in Windows Latin-1, explicitly state the encoding, otherwise the default OS encoding of the hoster is given.

BufferedReader br = new BufferedReader(new InputStreamReader(
        new FileInputStream(file), "Windows-1252"));

If the file is stored as resource, under /WEB-INF/classes/ you may also use

BufferedReader br = new BufferedReader(new InputStreamReader(
        getClass().getResourceAsStream("/files/BB.key"), "Windows-1252"));

In that case the file would reside under /WEB-INF/classes/files/BB.key.

Aravind R. Yarram

It is better to read the file as a classpath resource rather than a file system resource. This helps you to avoid hard-coding or parameterizing environment specific folder. Follow this post Reading file from classpath location for "current project"

Add this:

private static String currentDirectory = new File("").getAbsolutePath();

and change your BufferedReader to:

BufferedReader br = new BufferedReader(new FileReader(currentDirectory + "\\files\\BB.key"));

currentDirectory will contain whatever path the project directory is in (where you're running the program from).

If you reference a file by relative path (new FileReader("files/BB.key")), then it will resolve against the current work directory when executing your program.

What exactly do you try to achieve?

If you want to package a file with your program and then access this programmatically, put it on the classpath and load it as ressource with one of the Class.getResource... methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!