Javaはリソースの下のファイルパスを取得します

方法 1: ClassLoader.getResource() メソッドを使用する

String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getClassLoader().getResource(filePath);
String resourcePath = resourceUrl.getPath();

方法 2: ClassLoader.getResourceAsStream() メソッドを使用する

String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);

方法 3: Class.getResource() メソッドを使用する

String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getResource(filePath);
String resourcePath = resourceUrl.getPath();

方法 4: Class.getResourceAsStream() メソッドを使用する

String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getResourceAsStream(filePath);

問題の記録

リソースディレクトリ内のファイルパスを取得して戻ります

public String getResourcesPath(String filePath) {
    
    
        String resourcePath=null;
        try {
    
    
            Resource resource = new ClassPathResource(filePath);
            Path path = resource.getFile().toPath();
            resourcePath=path.toString();
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }
        return resourcePath;
    }

ファイル パスもここで取得できます。ローカルのみです。jar パッケージを使用すると、ファイルの特定のパスを取得できません。私の解決策は次のとおりです。

 public String getResourcesPath(String filePath) {
    
    
        String resourcePath=null;
        File file = new File(filePath);
        try {
    
    
            Resource resource = new ClassPathResource(filePath);
            InputStream inputStream = resource.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, file);
            resourcePath=file.getAbsolutePath();
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }
        return resourcePath;
    }

ストリームから取得

おすすめ

転載: blog.csdn.net/weixin_45735355/article/details/134160438