Programming

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

procodes 2020. 5. 10. 11:47
반응형

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


리소스의 텍스트 파일을 문자열로 읽는 데 도움이되는 유틸리티가 있습니까? 나는 이것이 대중적인 요구 사항이라고 생각하지만 인터넷 검색 후 유틸리티를 찾을 수 없습니다.


예, 구아바Resources수업 시간에 이것을 제공합니다 . 예를 들면 다음과 같습니다.

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

구아바와 같은 추가 종속성없이 이전 Stupid Scanner 트릭 oneliner를 사용할 수 있습니다 .

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

여러분, 정말로 필요하지 않으면 제 3 자 물건을 사용하지 마십시오. JDK에는 이미 많은 기능이 있습니다.


자바 7의 경우 :

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

구아바 에는 파일을 문자열로 읽는 "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 Skeet 이전 답변 에서와 같이 ).


순수하고 단순하며 항아리 친화적 인 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 파일의 리소스와 함께 작동합니다 .


불필요한 의존성을 피하십시오

항상 크고 뚱뚱한 라이브러리에 의존하지 않는 것이 좋습니다. 다른 작업에 이미 Guava 또는 Apache Commons IO를 사용하지 않는 한 파일에서 읽을 수 있도록 해당 라이브러리를 프로젝트에 추가하면 너무 많은 것 같습니다.

"간단한"방법? 농담 해

나는 순수한 Java가 이와 같은 간단한 작업을 수행 할 때 잘 작동하지 않는다는 것을 이해합니다. 예를 들어, Node.js의 파일에서 읽는 방법은 다음과 같습니다.

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

간단하고 읽기 쉽다 (사람들은 여전히 ​​대부분 무지 때문에 많은 의존성에 의존하기를 좋아하지만). 또는 파이썬에서 :

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

슬프지만 Java 표준에서는 여전히 간단하며 위의 방법을 프로젝트에 복사하여 사용하기 만하면됩니다. 나는 거기에서 무슨 일이 일어나고 있는지 이해하지 않아도됩니다. 왜냐하면 그것은 누구에게나 중요하지 않기 때문입니다. 그냥 작동합니다. 기간 :-)


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

import org.apache.commons.io.IOUtils;

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

apache-commons-io 의 유틸리티 이름은 FileUtils다음과 같습니다.

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

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

나는 종종이 문제를 스스로했다. 작은 프로젝트에 대한 의존성을 피하기 위해 공통점이 필요하지 않을 때 종종 작은 유틸리티 함수를 작성합니다. 다음은 파일의 내용을 문자열 버퍼에로드하는 코드입니다.

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());   

Specifying the encoding is important in that case, because you might have edited your file in UTF-8, and then put it in a jar, and the computer that opens the file may have CP-1251 as its native file encoding (for example); so in this case you never know the target encoding, therefore the explicit encoding information is crucial. Also the loop to read the file char by char seems inefficient, but it is used on a BufferedReader, and so actually quite fast.


You can use the following code form Java

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

If you want to get your String from a project resource like the file testcase/foo.json in src/main/resources in your project, do this:

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

Note that the getClassLoader() method is missing on some of the other examples.


Use Apache commons's FileUtils. It has a method readFileToString


I'm using the following for reading resource files from the 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() : "";
        }
    }
}

No third party dependencies required.


Here is my approach worked fine

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
    }
}

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;
    }
}

At least as of Apache commons-io 2.5, the IOUtils.toString() method supports an URI argument and returns contents of files located inside jars on the classpath:

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

Guava also has Files.readLines() if you want a return value as List<String> line-by-line:

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

Please refer to here to compare 3 ways (BufferedReader vs. Guava's Files vs. Guava's Resources) to get String from a text file.


With set of static imports, Guava solution can be very compact one-liner:

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

The following imports are required:

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

I've written readResource() methods here, to be able to do it in one simple invocation. It depends on the Guava library, but I like JDK-only methods suggested in other answers and I think I'll change these that way.


If you include Guava, then you can use:

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

(Other solutions mentioned other method for Guava but they are deprecated)


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

반응형