Java reads files in the resource directory

Java reads files in the resource directory

Put the file in the resouce directory

Insert image description here

code

import java.io.*;

public class FileUtilsTest {
    
    

    public static void main(String[] args) throws IOException {
    
    
        // 指定文件在classpath中的相对路径, maven 项目放 resource 目录
        String filePath = "123.txt";

        // 使用ClassLoader加载资源并获取InputStream
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream(filePath);

        if (inputStream != null) {
    
    
            // 使用BufferedReader读取文件内容
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
    
    
                String line;
                while ((line = reader.readLine()) != null) {
    
    
                    System.out.println(line); // 打印每一行内容
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            } finally {
    
    
                inputStream.close();
            }
        } else {
    
    
            System.out.println("文件未找到:" + filePath);
        }
    }
}

Guess you like

Origin blog.csdn.net/leafcat7/article/details/132732459