java.io.FileNotFoundException:尽管文件存在于src/main/resources中,但找不到类路径资源

4

enter image description here

我的XML文件位于src/main/resources目录下。我的spring代码如下:

import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.springframework.core.io.ClassPathResource;
import org.springframework.integration.xml.transformer.XsltPayloadTransformer;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BdeApplicationController {

    @GetMapping("/ping")
    @ResponseBody
    public String ping(@RequestParam(name="name", required=false, defaultValue="Stranger") String name) {
        return myFlow();
    }

    private String myFlow() {
        XsltPayloadTransformer transformer = getXsltTransformer();
        return transformer.transform(buildMessage(getXMLFileString())).toString();
    }

    private String getXMLFileString() {
        try {
            return Files.toString(new ClassPathResource("XML1.xml").getFile(), Charsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private XsltPayloadTransformer getXsltTransformer() {
        return new XsltPayloadTransformer(new ClassPathResource("XSLT1.xsl"));
    }

    protected Message<?> buildMessage(Object payload) {
        return MessageBuilder.withPayload(payload).build();
    }
}

运行该代码时,我得到以下异常:-
java.io.FileNotFoundException:类路径资源[XML1.xml]不能解析为绝对文件路径,因为它不驻留在文件系统中:jar:file:/Users/user/Documents/project/target/bde-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/XML1.xml
请问您能提供如何解决这个问题的建议吗?
2个回答

10

当你使用resource.getFile()时,你是在文件系统中查找文件,这就是为什么在运行jar文件时它不起作用。

尝试使用InputStream。

String data = "";
ClassPathResource resource = new ClassPathResource("/XML1.xml");
try {
    byte[] dataArr = FileCopyUtils.copyToByteArray(resource.getInputStream());
    data = new String(dataArr, StandardCharsets.UTF_8);
} catch (IOException e) {
    // do whatever
}

你是否正在像运行jar文件一样运行它? - jonhid
嗨,是的,我正在将它作为jar运行,你的解决方案现在有效 :) - Adi

0

您的jar归档文件中没有文件:请使用InputStream

一旦您获得资源(通过ClassPathResource),您应该使用getInputStream()来获取其内容,无论它位于何处。这种方式可以在您的IDE中工作(实际上是一个File),也可以在服务器上运行jar时(在jar归档文件内,不是确切地一个File)。

您只需要修改getXMLFileString()方法,使其使用InputStream而不是File:

private String getXMLFileString() {
    String xml;
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        xml = reader.lines().collect(Collectors.joining("\n"));
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        xml = null;
    }
    return new String(xml, Charsets.UTF_8);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接