1

I'm need to read from a file and write to a String array. I am a little confused by the forEach statement. How can I write to the String array, 1 for each line?

package input;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFile {

    public String[] currentBookData;

    public static void getBookData() throws IOException {
        try (Stream<String> stream = Files.lines(Paths.get("C:/test.txt"), Charset.defaultCharset())) {
            stream.forEach(System.out::println);
        } 

        catch (IOException ex) {
            System.out.println(ex.getMessage());
        }

    }
}

2 Answers 2

1

You can use either

stream.toArray();

or

String [] s = new String[0];
 stream.collect(Collectors.toList()).toArray(s);
Sign up to request clarification or add additional context in comments.

Comments

1

The Stream class provides a toArray() Method.

http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray-java.util.function.IntFunction-

If you just want to put the lines into a collection, take a look at this: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29

The readAllLines() method reads all lines and puts them into a List.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.