开发者

FileNotFoundException when ussing FileReader to find a resource in a java ee6 dynamic project

I am getting the all well known FileNotFoundException when i try to call a .txt file that holds some text. I used various path convinations, but i dont get the right one. Here is how i call it:

private String generateActivationLinkTemplate() {
    String htmlText = "";
    try {
        Scanner scanner = new Scanner(new FileReader(
                "/web/emailActivationTemplate.txt"));
        while (scanner.hasNextLine()) {
            htmlText += scanner.nextLine();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return htmlText;
}

The full path to the file looks like this:

 C:\jee6workspa开发者_开发知识库ce\BBS\WebContent\web\emailActivationTemplate.txt

How should i tell my program to find this file in the most flexible way?


One way - access to file through servlet context, f.e. i'm use in my Wicket project

final ServletContext ctx = ((WebApplication) getApplication()).getServletContext();
final File reportFile = new File(ctx.getRealPath("/reports/pivotTable.jasper"));

in your case

Scanner scanner = new Scanner(new FileReader(
            new File(ctx.getRealPath("/web/emailActivationTemplate.txt"))));

so you only need to get your servlet context in proper place Other way - try to access to file through classpath.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜