src/main/resources 中的 FileNotFoundException [英] FileNotFoundException in src/main/resources

查看:60
本文介绍了src/main/resources 中的 FileNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 src/main/resources 下的 maven 项目中放置了一个文件文件名只是 temp.txt.

i placed a file in my maven project under src/main/resources the files name is simply temp.txt.

当我尝试打开文件时:

BufferedReader br = new BufferedReader(new FileReader(new File("./temp.txt")));

我收到一个错误:

Exception in thread "main" java.io.FileNotFoundException: 	emp.txt

src/main/resources 下的所有文件都放在maven 下的类路径.那么为什么程序在这里找不到文件呢?

all files under src/main/resources are placed in the root folder of the classpath under maven. So why cant the program find the file here?

推荐答案

如果你要在类路径中打包文件,那么就从类路径中读取它.

If you're going to package the file in the class path, then read it as such.. from the class path.

Maven 结构

src
   main
       resources
               file.txt

构建后,文件被放置在类路径的根目录中.所以用

After it builds, the file gets placed in the root of the class path. So use

InputStream is = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

file.txt 前面的 / 将带您从类所在的任何包中找到根目录.

The / in front of file.txt will bring you to the root, from whatever package the class is in.

更新

测试示例

package com.underdogdevs.stackoverflow;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class TestResourceFile {

    public static void main(String[] args) throws IOException {
        InputStream is = TestResourceFile.class.getResourceAsStream("/test.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }
}

这篇关于src/main/resources 中的 FileNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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