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

查看:218
本文介绍了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: \temp.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天全站免登陆