CaffeineToCode
CaffeineToCode

Reputation: 830

How to write to String array with forEach statement

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

    }
}

Upvotes: 1

Views: 181

Answers (2)

null
null

Reputation: 5255

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.

Upvotes: 1

sol4me
sol4me

Reputation: 15698

You can use either

stream.toArray();

or

String [] s = new String[0];
 stream.collect(Collectors.toList()).toArray(s);

Upvotes: 1

Related Questions