java.io.FileNotFoundException:类路径资源,即使文件存在于src / main / resources中

时间:2018-04-06 03:08:38

标签: java spring spring-boot intellij-idea

enter image description here

我的src / main / resources目录下有我的XML文件。我的春天代码看起来像

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 /类!/XML1.xml

你能否建议我如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

当你使用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
}