-5

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

Clifford Fajardo
  • 1,357
  • 1
  • 17
  • 28
  • What did you try? Did you Google "Java read file" etc? – dabadaba Jan 30 '17 at 15:16
  • for reading as string see http://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file – Redlab Jan 30 '17 at 15:17
  • Why do you want to store it as a single string? That is an odd requirement. – bradimus Jan 30 '17 at 15:18
  • you can read the text file directly in an array – XtremeBaumer Jan 30 '17 at 15:19
  • This is probably homework, and you are asking us to do it for you. – RealSkeptic Jan 30 '17 at 15:23
  • The error is already in the premise. Why insisting on reading a file into a single `String`, if you already know that you actually want an array… – Holger Jan 30 '17 at 15:43
  • I was thinking of grabbing all of the text file contents as a string, trimming it & removing new lines & tabs for certain types of files I'm working with. I did read some docs, but a lot of the examples don't show the packages you need to import. I'm also getting used to reading the java docs. Yeah - very novice question, but hey that's why I am here to learn. – Clifford Fajardo Jan 30 '17 at 19:31

1 Answers1

1

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);
Mureinik
  • 297,002
  • 52
  • 306
  • 350