277

Is there a way to read a text file in the resource into a String?

I suppose this is a popular requirement, but I couldn't find any utility after Googling.

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Loc Phan
  • 4,304
  • 4
  • 29
  • 35
  • 1
    please clarify what you mean by "resource text file" vs "text file in resource" - it's not easy to understand what you are trying to achieve. – Mat May 20 '11 at 06:27
  • That's just a text file under classpath like "classpath*:mytext/text.txt" – Loc Phan May 20 '11 at 06:29
  • 9
    Since java11 there is a specific method for this: `Files.readString(Paths.get(getClass().getResource("foo.txt").toURI()), Charset.forName("utf-8"))` – Roberto Feb 20 '21 at 14:57
  • 1
    @Roberto your method works when I run my program from an exploded folder with classes, but when I package it into jar, `Paths.get(...)` throws `FileSystemNotFoundException` – morgwai Oct 09 '21 at 04:56
  • IOUtils.resourceToString("/foo/text.txt", StandardCharsets.UTF_8); – Daniel Hári Jun 20 '23 at 19:39

24 Answers24

330

Yes, Guava provides this in the Resources class. For example:

URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
Sergey
  • 3,253
  • 2
  • 33
  • 55
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 24
    @JonSkeet This is great, however for web applications it might not be the best solution, the implementation of `getResource` is using `Resource.class.getClassLoader` but in web applications, this might not be "your" class loader, so it's recommended (e.g. in [1]) to use `Thread.currentThread().getContextClassLoader().getResourceAsStream` instead (reference [1]: http://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream) – Eran Medan Jun 13 '13 at 20:21
  • 2
    @EranMedan: Yes, if you want the context classloader you'd want to use it explicitly. – Jon Skeet Jun 13 '13 at 20:24
  • 7
    In the special case when the resource is next to your class, you can do `Resources.toString(MyClass.getResource("foo.txt"), Charsets.UTF_8)` which guarantees the use of the correct class loader. – Bogdan Calmac Mar 05 '15 at 17:46
  • @Arne: What version of Java are you using? There may be something in Java 7 or Java 8... – Jon Skeet Jul 01 '16 at 13:54
  • @Arne: Well of course you *can* read your resource files without anything extra. Just create a `BufferedReader` around an `InputStreamReader` around your resource stream, read a chunk at a time and append it to a `StringBuilder`. You should be able to do the whole thing in about 15 lines of code, I should think. Looking around JDK 8, I can't see anything massively simpler though :( – Jon Skeet Jul 01 '16 at 14:16
  • @JonSkeet: Looks like Guava's `Resource.getResource` ([source](https://github.com/google/guava/blob/master/guava/src/com/google/common/io/Resources.java#L195)) now uses your recommended method. – firyice Oct 25 '16 at 00:51
  • Note for Java 7 and later: `Charsets` should be treated as deprecated; use `java.nio.charset.StandardCharsets` instead. – b3000 Oct 18 '18 at 13:33
  • 6
    `com.google.common.io.Resources` is marked unstable according to SonarQube – Ghilteras Jun 11 '19 at 01:00
  • @Ghilteras: It looks like it still has the `@Beta` tag - but personally I'd be surprised if it was removed at this point. – Jon Skeet Jun 11 '19 at 05:20
  • 3
    `guava` has change the implementation. For guava 23 the implementation likes following. `ClassLoader loader = MoreObjects.firstNonNull( Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader());` – xxy Feb 22 '20 at 12:18
  • @xxy alas, this latest implementation is still not sufficient for my maven plugin development where the current thread loader is `org.codehaus.plexus.classworlds.realm.ClassRealm`. I still resort to using `getClass().getResource(..)` (as pointed by @Bogdan Calmac above) – Alex Apr 01 '20 at 18:00
  • Be careful, this function has an issue in windows, if I use File.separator (in windows \) throws exception. I have to replace it with "\" in order to make it work. E.g.: "texts/mytextfile.txt". I was struggling with this few hours... – Lyoneel Sep 29 '21 at 22:57
  • There are way better solutions than using a huge library like Guava. Plain java is a better solution. – Brain Nov 23 '22 at 14:13
212

You can use the old Stupid Scanner trick oneliner to do that without any additional dependency like guava:

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

Guys, don't use 3rd party stuff unless you really need that. There is a lot of functionality in the JDK already.

matt freake
  • 4,877
  • 4
  • 27
  • 56
akosicki
  • 2,253
  • 1
  • 12
  • 6
  • 54
    Avoiding 3rd party is a reasonable principle. Unfortunately the core library seems allergic to modeling real-life use cases. Look at Java 7's Files, and tell me why reading everything from a classpath resource wasn't included there? Or at least using a standardized 'filesystem'. – Dilum Ranatunga Mar 07 '14 at 18:36
  • 4
    Is it - or is it not - necessary to close the stream as well? Guava internally closes the stream. – virgo47 Nov 12 '14 at 13:50
  • Worked beautifully for me too! I agree about the 3rd party thing also: In to many answers, the default response always seems to be to use some third party library - be it from Apache or someone else. – Terje Dahl Apr 05 '15 at 08:01
  • 2
    change ```CartApplication.class.getResourceAsStream``` to ```CartApplication.class.getClassLoader().getResourceAsStream``` to load resources in the current jar..like srm/test/resources – Chris DaMour Feb 27 '16 at 06:38
  • 10
    While I've used this, I completely disagree on avoiding 3rd party packages. The fact that in Java, the only way to easily read a file to string is with the scanner trick is pretty sad. The alternative to using a 3rd party lib is that everyone will just create their own wrappers. Guava for IO hands down wins if you have a lot of needs for this kind of operation. Where I WILL agree is that you shouldn't import a 3rd party package if you only have one place in your code where you want to do this. That would be overkill imo. – Kenny Cason Mar 30 '16 at 22:21
  • Nice solution, however it does not work when the resource/stream is empty, as the Scanner will throw an NoSuchElementException in that case. To make the code work in all cases wrap the statement in a try-catch and "use" an empty space when caught. Sadly this no longer is a one-liner. – Udo Borkowski Dec 05 '18 at 19:39
125

Pure and simple, jar-friendly, Java 8+ solution

This simple method below will do just fine if you're using Java 8 or greater:

/**
 * 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()));
        }
    }
}

And it also works with resources in jar files.

About text encoding: InputStreamReader will use the default system charset in case you don't specify one. You may want to specify it yourself to avoid decoding problems, like this:

new InputStreamReader(isr, StandardCharsets.UTF_8);

Avoid unnecessary dependencies

Always prefer not depending on big, fat libraries. Unless you are already using Guava or Apache Commons IO for other tasks, adding those libraries to your project just to be able to read from a file seems a bit too much.

Community
  • 1
  • 1
Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104
  • 7
    @zakmck please try to keep your comments constructive. As you grow up as a mature developer, you learn that sometimes you do want to "reinvent the wheel". For instance, you may need to keep your binary below something threshold size. Libraries often make your application size grow by orders of magnitude. One could argue just the opposite of what you said: "No need to write code. Yeah, let's just import libraries every time". Would you really prefer importing a library just to save you 3 lines of code? I bet that adding the library will increase your LOC by more than that. The key is balance. – Lucio Paiva Dec 08 '17 at 12:24
  • Btw, I just saw you posted an answer here as well saying that you wrote some methods in your own library depending on Guava but you "like JDK-only methods suggested in other answers and [you] think [you]'ll change these that way". Good to know, glad that I could help :-) – Lucio Paiva Dec 08 '17 at 12:52
  • [Would you really prefer importing a library just to save you 3 lines of code] ==> Given that I'm running stuff on cloud servers, each having a minimum of 16GB RAM, of course I do it. I would use C (or Assembler) if I had C=64 hardware requirements. In nowadays world having readable, factorised, less error-prone code is usually way more important than saving a few KBs. – zakmck Dec 08 '17 at 14:54
  • 6
    Well, not every one is running stuff on the cloud. There are embedded systems everywhere running Java, for example. I just don't see your point in criticizing answers that provide totally valid approaches, given that you mention yourself that you're going to accept the suggestion to use JDK directly in your own code. Anyway, let's please try to keep comments strictly to help improve answers, not to discuss opinions. – Lucio Paiva Dec 08 '17 at 15:17
  • My criticism is only to the "There's no need for big, fat libraries" part. Guava or Apache Commons are just a few KBs (or MBs, for what matters) and, in most cases, reusing them when you need functionality they already implement is preferable to saving a few KBs (maybe not good for embedded systems, but that's not the typical JDK usage). – zakmck Dec 08 '17 at 17:16
  • I plan to reuse the JDK to implement my readResource() methods, because I don't see any simple method in JDK to do so, as a minimum you need to write a long ugly line every time, or worse, reimplement your method above every time. So, using my jUtils lib would make it the "big fat library" around :-) BTW: I've split it recently, cause it had become too big and pulling too many dependencies, so I too care about component sizes, I'm just not obsessed with it at the expense of good software engineering practices :-) – zakmck Dec 08 '17 at 17:19
  • 1
    Good JDK-only solution. I would only add check if `InputStream` variable `is` is `null` or not. – scrutari Apr 09 '18 at 21:02
  • Good catch, @ArtOfWarfare (and also @dimplex). Edited the code to use try-with-resources statement. – Lucio Paiva Aug 28 '19 at 17:10
  • @ArtOfWarfare I totally missed it, thanks for pointing that out. I took the chance and rewrote most of the answer. I also dropped the non-static method (the static one works for all cases, so let's keep it simple). – Lucio Paiva Aug 29 '19 at 10:02
  • Very nice native solution. I'm using aws lambdas so this was useful in cutting down dependencies. Possible small point for improvement, spotbugs warns on not passing in the charsetName. Easily resolved by calling `public InputStreamReader(InputStream in, String charsetName)`. Thanks for this. – Robert Bain Oct 24 '19 at 19:10
  • Another small point, this doesn't work for me in the jar uploaded to aws. I needed to pass the class in and get the class loader from there, like this: `public static String getResourceFileAsString(Class> clazz, String fileName) { ClassLoader classLoader = clazz.getClassLoader();` – Robert Bain Oct 25 '19 at 16:46
  • 1
    @RobertBain I edited the answer to add info about the charset warning. Let me know if you find out what went wrong with the class loader in AWS so I can add it to the answer as well. Thanks! – Lucio Paiva Oct 26 '19 at 18:23
  • Thanks @LucioPaiva for some reason `ClassLoader.getSystemClassLoader()` doesn't cut the mustard (you get a `null` `InputStream`) - you have to pass the in the class as a method argument and call `clazz.getClassLoader()`. This does the trick. – Robert Bain Oct 26 '19 at 22:10
  • Just for comparison, in Groovy it's... `String s = new File("some-file.txt").text` Just my opinion, but, if something as basic as reading a file into a string is more than one line, it seems like a red flag. – roninjoe May 15 '20 at 15:48
  • 1
    I believe this should be the accepted answer. No deps, modern, simple and readable. Plus it offers alternatives to Java code. – wooseop Feb 07 '22 at 09:30
  • Hi @LucioPaiva, I'm having a little trouble understanding the line 'return reader.lines().collect(Collectors.joining(System.lineSeparator()));' What does it look like if we remove the fancy Java 8 stream stuff and go full boilerplate? I'd just like to see how it manages to turn the inputstream into a String. Just another newbie trying to learn, sorry if the question is dumb :) – Evil Washing Machine May 18 '22 at 15:19
117

For java 7:

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

For Java 11:

Files.readString(Paths.get(getClass().getClassLoader().getResource("foo.txt").toURI()));
FoldFence
  • 2,674
  • 4
  • 33
  • 57
Kovalsky Dmitryi
  • 1,420
  • 1
  • 9
  • 12
58

yegor256 has found a nice solution using Apache Commons IO:

import org.apache.commons.io.IOUtils;

String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
                               "UTF-8");
Community
  • 1
  • 1
Stefan Endrullis
  • 4,150
  • 2
  • 32
  • 45
  • I prefer "" to this in-case this is unavailable – user833970 Jan 15 '15 at 19:25
  • 14
    Just as compact, but with proper closing of the input stream: `IOUtils.toString(this.getClass().getResource("foo.xml"), "UTF-8")`. – Bogdan Calmac Mar 05 '15 at 17:52
  • 2
    If this solution doesn't work, try adding `getClassLoader()` to the method chain: `String text = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("foo.xml"), StandardCharsets.UTF_8);` – Abdull Oct 04 '17 at 10:04
  • 4
    Another example with IOUtils: `IOUtils.resourceToString("/foo.xml", StandardCharsets.UTF_8);` – Alex Rewa Aug 18 '20 at 07:58
55

Guava has a "toString" method for reading a file into a String:

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

This method does not require the file to be in the classpath (as in Jon Skeet previous answer).

Community
  • 1
  • 1
Luciano Fiandesio
  • 10,037
  • 10
  • 48
  • 56
  • 2
    Or if it's an input stream, guava has a nice way for this as well `String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));` – Eran Medan Jun 13 '13 at 20:10
  • 1
    This is deprecated in Guava 24.1 – Andrey Apr 24 '18 at 18:54
41

apache-commons-io has a utility name FileUtils:

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

String content = FileUtils.readFileToString(myFile, "UTF-8");  // or any other encoding
Edd
  • 8,402
  • 14
  • 47
  • 73
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • 2
    Why do one have to specify the encoding, i don't get that. If I read the file, i just want what is in it, it should figure out what encoding it is like my editor does. When I open in Notepad or ++, I dont tell it what encoding it should use. I am using this method and then afterwards writeStringToFile ... but the contents differ. I get strange tokens in the cloned file.. i don't get why I should have to specify an encoding. – mjs Dec 20 '11 at 14:47
  • 13
    @Hamidan, choosing the right encoding is a very complex algorithm. It is often implemented in text editor but they sometimes fail to detect the correct encoding. I would not expect a file reading API to embed such complex algorithm to read my file. – Vincent Robert Jan 17 '12 at 11:06
  • 1
    @SecretService Also, those algorithms make use of information like the operating system's language, locale and other regional settings which means that reading a file without specifying an encoding may work on your setup but not on someone else's. – Feuermurmel Apr 28 '14 at 08:26
  • Apache [FileUtils](http://commons.apache.org/proper/commons-io/description.html#FileUtils).[readLines](http://avajava.com/tutorials/lessons/how-do-i-get-a-list-of-the-lines-in-a-file-using-commons-io.html)(file) & copyURLToFile(URL, tempFile). – Yash Feb 25 '16 at 10:51
  • 1
    Sorry for downvoting, but I don't like answers that add big dependencies to trivial problems. – Arne Jul 01 '16 at 13:54
  • 2
    I don't think this will work if the resource is found inside a jar. Then it won't be a file. – Ville Oikarinen May 09 '18 at 09:08
36

I like akosicki's answer with the Stupid Scanner Trick. It's the simplest I see without external dependencies that works in Java 8 (and in fact all the way back to Java 5). Here's an even simpler answer if you can use Java 9 or higher (since InputStream.readAllBytes() was added at Java 9):

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

If you're concerned about the filename being wrong and/or about closing the stream, you can expand this a little:

String text = null;
InputStream stream = AppropriateClass.class.getResourceAsStream("foo.txt");
if (null != stream) {
    text = stream.readAllBytes();
    stream.close()
}
Gary Sheppard
  • 4,764
  • 3
  • 25
  • 35
  • 3
    the best answer yet so low rated... – morgwai Oct 09 '21 at 06:02
  • @morgwai agreed and it raises the question of how SO considers recency in its weighting of answers to decide how high up the page to put them – Lucas Ross Sep 15 '22 at 16:33
  • 1
    `getResourceAsStream` stream is not closed properly. Also, unfriendly exception on wrong filenames – R A Feb 23 '23 at 14:16
  • @RA good point. I added a version that includes null-checking and closing the stream. – Gary Sheppard Feb 23 '23 at 14:27
  • @GarySheppard `readAllBytes` might throw an exception resulting in stream not being closed. I'd suggest you use try-with-resources and leave a single answer. – R A Feb 23 '23 at 14:36
18

You can use the following code form Java

new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Raghu K Nair
  • 3,854
  • 1
  • 28
  • 45
16

I often had this problem myself. To avoid dependencies on small projects, I often write a small utility function when I don't need commons io or such. Here is the code to load the content of the file in a string buffer :

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.

Harry Karadimas
  • 177
  • 1
  • 2
5

Here's a solution using Java 11's Files.readString:

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);
    }
}
Dillon Ryan Redding
  • 1,213
  • 12
  • 17
4

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.

Witbrock
  • 502
  • 2
  • 5
  • 12
2

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.

BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
2

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(), ...)
user1050755
  • 11,218
  • 4
  • 45
  • 56
2

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

Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
  • 1
    File works only for classpath resources that are, well, files. Not if they are elements in a .jar file, or part of a fat jar, one one of the other classloader implementations. – toolforger Apr 30 '20 at 13:37
1

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
Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
1
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;
    }
}
sklimkovitch
  • 251
  • 4
  • 8
0

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

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)

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
jolumg
  • 714
  • 2
  • 15
  • 31
0

The following cods work for me:

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");
Vikki
  • 1,897
  • 1
  • 17
  • 24
0

I made NO-dependency static method like this:

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
}
Espresso
  • 5,378
  • 4
  • 35
  • 66
0

I like Apache commons utils for this type of stuff and use this exact use-case (reading files from classpath) extensively when testing, especially for reading JSON files from /src/test/resources as part of unit / integration testing. e.g.

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

}

For testing purposes, it can be nice to catch the IOException and throw a RuntimeException - your test class could look like e.g.

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

        // Use json as part of test ...
    }
bobmarksie
  • 3,282
  • 1
  • 41
  • 54
  • `Charset.defaultCharset()` is platform-dependent, encoding should be stated explicitely – R A Feb 23 '23 at 12:14
0

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.

philipjkim
  • 3,999
  • 7
  • 35
  • 48
-1
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");