LynAs
LynAs

Reputation: 6537

Read file from a folder inside the project directory

In a JSP project I am reading a file from directory. If i give the full path then i can easily read the file

BufferedReader br = new BufferedReader(new FileReader("C:\\ProjectFolderName\\files\\BB.key"));

but i don't want to write the full path instead i just want to give the folder name which contains the file, like bellow.

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

How to do this?

String currentDirectory = new File("").getAbsolutePath();
System.out.println(currentDirectory);
BufferedReader br = new BufferedReader(new FileReader(currentDirectory + "\\files\\BB.key"));

I tried the above still cant read from file

the print line gives the following output

INFO: C:\Program Files\NetBeans 7.3

Upvotes: 2

Views: 22950

Answers (4)

Joop Eggen
Joop Eggen

Reputation: 109557

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.

Upvotes: 4

Aaron
Aaron

Reputation: 1016

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).

Upvotes: 2

Vampire
Vampire

Reputation: 38669

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.

Upvotes: 0

Aravind Yarram
Aravind Yarram

Reputation: 80176

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"

Upvotes: 3

Related Questions