programing

리소스 텍스트 파일을 문자열(Java)로 읽기 위한 유틸리티

minecode 2022. 12. 20. 21:35
반응형

리소스 텍스트 파일을 문자열(Java)로 읽기 위한 유틸리티

리소스 내의 텍스트 파일을 문자열로 읽는 데 도움이 되는 유틸리티가 있습니까?이것은 일반적인 요구 사항이라고 생각합니다만, 구글링 후에 유용성을 찾을 수 없었습니다.

네, 구아바가 수업시간에 이걸 제공합니다.예를 들어 다음과 같습니다.

URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);

guava와 같은 추가 종속성 없이 오래된 Studp Scanner 트릭을 사용할 수 있습니다.

String text = new Scanner(AppropriateClass.class.getResourceAsStream("foo.txt"), "UTF-8").useDelimiter("\\A").next();

여러분, 서드파티 물건은 꼭 필요한 게 아니면 쓰지 마세요.JDK에는 이미 많은 기능이 있습니다.

Java 7의 경우:

new String(Files.readAllBytes(Paths.get(getClass().getResource("foo.txt").toURI())));

Java 11의 경우:

Files.readString(Paths.get(getClass().getResource("foo.txt").toURI()));

순수하고 심플한 항아리 친화적인 Java 8+ 솔루션

Java 8 이상을 사용하는 경우 아래의 간단한 방법으로 충분합니다.

/**
 * Reads given resource file as a string.
 *
 * @param fileName path to the resource file
 * @return the file's contents
 * @throws IOException if read fails for any reason
 */
static String getResourceFileAsString(String fileName) throws IOException {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    try (InputStream is = classLoader.getResourceAsStream(fileName)) {
        if (is == null) return null;
        try (InputStreamReader isr = new InputStreamReader(is);
             BufferedReader reader = new BufferedReader(isr)) {
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        }
    }
}

또한 jar 파일의 리소스와도 연동됩니다.

인코딩에 :InputStreamReader를 지정하지 않으면 기본 시스템 문자 집합이 사용됩니다.다음과 같은 디코딩 문제를 피하기 위해 직접 지정할 수 있습니다.

new InputStreamReader(isr, StandardCharsets.UTF_8);

불필요한 의존관계 회피

크고 두꺼운 라이브러리에 의존하지 않는 것을 항상 선호합니다.이미 Guava 또는 Apache Commons IO를 다른 작업에 사용하고 있지 않는 한 파일에서 읽을 수 있도록 이러한 라이브러리를 프로젝트에 추가하는 것은 좀 무리인 것 같습니다.

'간단한' 방법?농담으로 하시는 말씀이죠?

이와 같은 간단한 작업을 할 때 순수 자바가 잘 되지 않는다는 것을 알고 있습니다.예를 들어, Node.js의 파일에서 다음과 같이 읽습니다.

const fs = require("fs");
const contents = fs.readFileSync("some-file.txt", "utf-8");

심플하고 읽기 쉽다(다만 사람들은 여전히 많은 의존관계에 의존하는 것을 좋아한다, 대부분 무지에 기인한다).또는 Python의 경우:

with open('some-file.txt', 'r') as f:
    content = f.read()

슬픈 일이지만, Java의 표준으로서는 여전히 간단하며, 위의 방법을 프로젝트에 복사하여 사용하기만 하면 됩니다.그 안에서 무슨 일이 일어나고 있는지 알려달라고 부탁하지도 않아요. 왜냐하면 그건 누구에게나 정말 중요치 않거든요.동작합니다.기간 :-)

Guava에는 파일을 문자열로 읽기 위한 "toString" 메서드가 있습니다.

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);

이 메서드에서는 파일이 클래스 경로에 있을 필요가 없습니다(Jon Sket의 이전 응답과 같습니다.

yegor256Apache Commons IO를 사용하여 적합한 솔루션을 찾았습니다.

import org.apache.commons.io.IOUtils;

String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
                               "UTF-8");

apache-vario에는 유틸리티 이름이 있습니다.FileUtils:

URL url = Resources.getResource("myFile.txt");
File myFile = new File(url.toURI());

String content = FileUtils.readFileToString(myFile, "UTF-8");  // or any other encoding

Java에서 다음 코드 형식을 사용할 수 있습니다.

new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));

저도 자주 이런 문제가 있었어요.작은 프로젝트에 의존하지 않기 위해 공통 io 등이 필요 없을 때 작은 유틸리티 기능을 쓰는 경우가 많습니다.다음은 문자열 버퍼에 파일 내용을 로드하는 코드입니다.

StringBuffer sb = new StringBuffer();

BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("path/to/textfile.txt"), "UTF-8"));
for (int c = br.read(); c != -1; c = br.read()) sb.append((char)c);

System.out.println(sb.toString());   

경우 UTF-8에서 파일을 편집하여 jar에 넣고 파일을 여는 컴퓨터에는 CP-1251이 네이티브파일 인코딩(예를 들어)으로 설정되어 있을 수 있기 때문에 이 경우 타깃 인코딩을 알 수 없기 때문에 명시적인 인코딩 정보가 중요합니다.또한 파일 문자를 문자로 읽는 루프는 비효율적인 것처럼 보이지만 BufferedReader에서 사용되므로 실제로는 매우 빠릅니다.

나는 아코식키의 바보같은 스캐너 트릭에 대한 대답이 좋다.Java 8(그리고 Java 5까지)에서 작동하는 외부 종속성이 없는 가장 간단한 방법입니다.Java 9 이상을 사용할 수 있는 경우(다음은InputStream.readAllBytes()Java 9 서 java java java java 。

String text = new String(AppropriateClass.class.getResourceAsStream("foo.txt")
    .readAllBytes());

프로젝트의 src/main/resources에 있는 testcase/foo.json 파일과 같은 프로젝트 리소스에서 문자열을 가져오려면 다음과 같이 하십시오.

String myString= 
 new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));

다른 예에서는 getClassLoader() 메서드가 누락되어 있습니다.

Apache Commons의 FileUtils를 사용합니다.readFileToString 메서드가 있습니다.

하다에서 때 과 같습니다.classpath:

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;

public class ResourceUtilities
{
    public static String resourceToString(String filePath) throws IOException, URISyntaxException
    {
        try (InputStream inputStream = ResourceUtilities.class.getClassLoader().getResourceAsStream(filePath))
        {
            return inputStreamToString(inputStream);
        }
    }

    private static String inputStreamToString(InputStream inputStream)
    {
        try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
        {
            return scanner.hasNext() ? scanner.next() : "";
        }
    }
}

서드파티 의존관계는 불필요합니다.

적어도 Apache commons-io 2.5 이후 IOUtils.toString() 메서드는 URI 인수를 지원하며 클래스 경로의 jar 내에 있는 파일의 내용을 반환합니다.

IOUtils.toString(SomeClass.class.getResource(...).toURI(), ...)

Java 11을 사용한 솔루션은 다음과 같습니다.

public class Utils {
    public static String readResource(String name) throws URISyntaxException, IOException {
        var uri = Utils.class.getResource("/" + name).toURI();
        var path = Paths.get(uri);
        return Files.readString(path);
    }
}

정적 Import 세트를 사용하여 Guava 솔루션은 매우 콤팩트한 원라이너로 만들 수 있습니다.

toString(getResource("foo.txt"), UTF_8);

다음의 Import가 필요합니다.

import static com.google.common.io.Resources.getResource
import static com.google.common.io.Resources.toString
import static java.nio.charset.StandardCharsets.UTF_8
package test;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            String fileContent = getFileFromResources("resourcesFile.txt");
            System.out.println(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //USE THIS FUNCTION TO READ CONTENT OF A FILE, IT MUST EXIST IN "RESOURCES" FOLDER
    public static String getFileFromResources(String fileName) throws Exception {
        ClassLoader classLoader = Main.class.getClassLoader();
        InputStream stream = classLoader.getResourceAsStream(fileName);
        String text = null;
        try (Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) {
            text = scanner.useDelimiter("\\A").next();
        }
        return text;
    }
}

에는 구아바도 .Files.readLines()을 반환할 List<String>"이것들"은 다음과 같습니다.

List<String> lines = Files.readLines(new File("/file/path/input.txt"), Charsets.UTF_8);

3가지 방법을 비교하려면 여기를 참조하십시오.BufferedReadervs.Guava의Filesvs.Guava의Resources)를 취득하다String텍스트 파일에서 가져옵니다.

여기 내 접근 방식이 잘 작동했습니다.

public String getFileContent(String fileName) {
    String filePath = "myFolder/" + fileName+ ".json";
    try(InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
        return IOUtils.toString(stream, "UTF-8");
    } catch (IOException e) {
        // Please print your Exception
    }
}

Guava를 포함할 경우 다음을 사용할 수 있습니다.

String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();

(기타 솔루션은 Guava에 대해 다른 방법을 언급했지만 권장되지 않음)

다음의 코드가 유효합니다.

compile group: 'commons-io', name: 'commons-io', version: '2.6'

@Value("classpath:mockResponse.json")
private Resource mockResponse;

String mockContent = FileUtils.readFileToString(mockResponse.getFile(), "UTF-8");

NO-dependency static 메서드를 다음과 같이 설정했습니다.

import java.nio.file.Files;
import java.nio.file.Paths;

public class ResourceReader {
    public  static String asString(String resourceFIleName) {
        try  {
            return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}

Apache Commons utils for this type을 좋아하며 테스트 시 특히 JSON 파일을 읽을 때 이 정확한 사용 사례(classpath에서 파일 읽기)를 광범위하게 사용합니다./src/test/resources유닛 / 통합 테스트의 일부로서.

public class FileUtils {

    public static String getResource(String classpathLocation) {
        try {
            String message = IOUtils.toString(FileUtils.class.getResourceAsStream(classpathLocation),
                    Charset.defaultCharset());
            return message;
        }
        catch (IOException e) {
            throw new RuntimeException("Could not read file [ " + classpathLocation + " ] from classpath", e);
        }
    }

}

테스트의 목적으로는, 다음의 정보를 입수하는 것이 좋을 수 있습니다.IOException그리고 던지다RuntimeException- 테스트 클래스는 예를 들어 다음과 같을 수 있습니다.

    @Test
    public void shouldDoSomething () {
        String json = FileUtils.getResource("/json/input.json");

        // Use json as part of test ...
    }
public static byte[] readResoureStream(String resourcePath) throws IOException {
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    InputStream in = CreateBffFile.class.getResourceAsStream(resourcePath);

    //Create buffer
    byte[] buffer = new byte[4096];
    for (;;) {
        int nread = in.read(buffer);
        if (nread <= 0) {
            break;
        }
        byteArray.write(buffer, 0, nread);
    }
    return byteArray.toByteArray();
}

Charset charset = StandardCharsets.UTF_8;
String content = new   String(FileReader.readResoureStream("/resource/...*.txt"), charset);
String lines[] = content.split("\\n");

언급URL : https://stackoverflow.com/questions/6068197/utils-to-read-resource-text-file-to-string-java

반응형