FileCopyUtils

FileCopyUtils - org.springframework.util.FileCopyUtils

It is a part of the Spring Framework's utility package. It provides static methods to perform file copy operations. This utility offer's methods for copying the contents of an InputStream to an OutputStream, as well as copying the contents of a file to another file or stream.

  • Copying contents from a file to a variable of String type.

Create 2 sample files (for e.g. SampleXmlResponse.xml and SampleJsonResponse.json) inside mocks folder.

SampleJsonResponse.jsonSampleXmlResponse.xml

Add logic in the main application class and execute the code.

package org.example;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.util.FileCopyUtils;

import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
public class Application {

    private static final String SUB_DIRECTORY = "mocks";
    private static final String XML_FILENAME = "SampleXmlResponse.xml";
    private static final String JSON_FILENAME = "SampleJsonResponse.json";

    public static void main(String[] args) {
        log.info("Mock XML Response:\n{}", getMockResponse(XML_FILENAME));
        log.info("Mock JSON Response:\n{}", getMockResponse(JSON_FILENAME));
    }

    @SneakyThrows
    public static String getMockResponse(String fileName) {
        var resourceLoader = new DefaultResourceLoader();
        var resource = resourceLoader.getResource(String.format("classpath:%s/%s", SUB_DIRECTORY, fileName));
        return FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
    }
}

Last updated