从项目目录中的文件夹中读取文件 [英] Read file from a folder inside the project directory

查看:213
本文介绍了从项目目录中的文件夹中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JSP项目中
我正在从目录中读取文件。如果我给出完整路径,那么我可以轻松读取文件

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"));

怎么做?

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

打印行提供以下输出

INFO:C:\Program Files \ NetBeans 7.3

INFO: C:\Program Files\NetBeans 7.3

推荐答案

使用

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

这将URL路径相对(因此为/)从Web内容目录转换为文件系统文件。

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

对于便携式Web应用程序,并且知道该文件在Windows Latin-1中,请明确说明编码,否则将给出主机的默认OS编码。 / p>

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"));

如果文件存储为资源,在/ WEB-INF / classes /下你也可以使用

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"));

在这种情况下,文件将驻留在/WEB-INF/classes/files/BB.key下。

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

这篇关于从项目目录中的文件夹中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆