lambda - Java - Reading a txt file line by line -


this question has answer here:

so have simple code i'm trying read file line line:

if(new file(filesdir).listfiles() != null){     for(file file : new file(filesdir).listfiles()){         try {             stream<string> stream = files.lines(paths.get(file.getabsolutepath()));             for(int = 0 ; < stream.toarray().length; i++){                 system.out.println(stream.toarray()[i]);             }             stream.close();         } catch (ioexception e) {             // todo auto-generated catch block             e.printstacktrace();         }        } } 

but when reaches sysout throws exception:

exception in thread "main" java.lang.illegalstateexception: java.lang.illegalstateexception: stream has been operated upon or closed

caused by: java.lang.illegalstateexception: stream has been operated upon or closed

every example find uses lambda expressions, don't think that's way, or it?

stream alternative using loop. can't use stream more once. if use stream more once calling toarray() twice per line of input insanely expensive.

what can is

try (stream<string> stream = files.lines(file.topath())) {     stream.foreach(system.out::println); } 

note: significant advantage of using approach can print file reads it. means no matter how big file is, can still read it. if use collection or array every line, size of file read limited amount of memory have.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -