Search code examples
javastringjava-8java-7text-manipulation

How to read txt file and save as a single string in java in order to split it by a certain character


I'm new to to java language & am finding trouble finding to:

1. read a txt file
2. save entire txt file as single string
3. once I have the txt file content as a string, break the string (by a certain character such as a new line) into an array of strings that I can work with.

If you may include the import statements that are required, that would be helpful as well as a new java programmer.

I was working with the BufferedReader but I believe that only gives me the current line to work with.

I did see that BufferedReader had a lines() method which returns a stream of Stream<String>.


Solution

  • Files#lines returns a stream of all the lines in the file. You could join these lines to a single string, and then split it according to the separator:

    String separator = ":"; // for example...
    String entireFile = 
        Files.lines(Paths.get("file.txt")).collect(Collectors.joining());
    String[] separated = entireFile.split(separator);