Java在eclipse中读取文本文件

标签 java eclipse spring

我正在尝试读取不同包中但在同一项目中可用的文本文件,但总是将 InputStream 设为 null。

public class ReadFileApp {

    public static void main(String[] args) {

        Thread currentThread = Thread.currentThread();
        ClassLoader classLoader = currentThread.getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("/com/rpsoft/response/fileOneResponse.txt");

        String response = null;
        try {
            response = new String(FileCopyUtils.copyToByteArray(inputStream));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Current Thread : " + currentThread);
        System.out.println("Class Loader : " + classLoader);
        System.out.println("InputStream : "+ inputStream);
        System.out.println("Response : " + response);
    }
}

获取异常:

Exception in thread "main" java.lang.IllegalArgumentException: No InputStream specified
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.util.FileCopyUtils.copy(FileCopyUtils.java:106)
    at org.springframework.util.FileCopyUtils.copyToByteArray(FileCopyUtils.java:156)
    at com.rpsoft.filetransport.ReadFileApp.main(ReadFileApp.java:18)

最佳答案

您可以根据项目中的文件位置尝试任何一种。

// Read from same package 
getClass().getResourceAsStream("fileOneResponse.txt")

// Read from resources folder parallel to src in your project
new File("resources/fileOneResponse.txt")

// Read from src/resources folder
getClass().getResource("/resources/fileOneResponse.txt")

// Read from src/resources folder
getClass().getResourceAsStream("/resources/fileOneResponse.txt")

关于Java在eclipse中读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24269523/

相关文章:

java - hibernate 无PK

java - ConcurrentHashMap 和 putAll() 方法

php - Eclipse 表达式调试面板将数组截断为 31 个元素

java - 组件扫描无法检测到接口(interface)bean?

java - org.springframework.beans.factory.NoSuchBeanDefinitionException : No unique bean of type [org.quartz.JobDetail]已定义

java - Spring Controller 方法被调用两次

java - 无法在 Java 正则表达式中使用 '-' 字符,它在给定文本中找不到模式

java - 如何找到 "B"+ 最多 6 个符号

java - 尝试在 Eclipse 中添加谷歌视觉教程库时出现 Maven 错误

c++ - 在 OS X (C++) 中设置 Eclipse 错误 : launch failed, 二进制文件未找到?