Path: csiph.com!eeepc.pasdenom.info!news.pasdenom.info!news.dougwise.org!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!weretis.net!feeder4.news.weretis.net!news.albasani.net!not-for-mail From: Lew Newsgroups: comp.lang.java.programmer Subject: Re: Shortest way to read all lines (one by one) from a text file? Date: Fri, 11 Feb 2011 07:51:27 -0500 Organization: albasani.net Lines: 43 Message-ID: References: <4d54f158$0$6975$9b4e6d93@newsspool4.arcor-online.net> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: news.albasani.net m2nXG5UzaVNzJLxNNH1Lqg+caLk4MAuhyU8GSk93egCp3NGseFC6NNUZMK49WDrNSE9O1pdadR3iqKGgDRi+dWkaw09tIo0DtMLJauT+mu15bNVwpfUnnj5GhM3zi24U NNTP-Posting-Date: Fri, 11 Feb 2011 12:50:44 +0000 (UTC) In-Reply-To: Cancel-Lock: sha1:DJWJGcWkYHkusyaUDUTpFrbutM0= User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101208 Thunderbird/3.1.7 Injection-Info: news.albasani.net; logging-data="tbouizAeC2MypHNaF/6Vkx58MXnIq+9wDwjj+kRofZG8ucIFonGZaO2cXJfQb1lclm/Vi9w7uOnasKGZftLCZ+b0sPcCc3xAeFLI2CLcNwEyxtiwAh5i1naLaBx83PFI"; mail-complaints-to="abuse@albasani.net" Xref: csiph.com comp.lang.java.programmer:25827 Robin Wenger wrote: >> Ok, I know in general a way to read text lines ony-by-one from a file into a >> string variable. >> But I miss somehow a short one-liner like: >> >> foreach(String currentline : file("D:\test\myfile.txt")) { >> .... >> } >> >> Is there something like this in Java? >> What would be the shortest way otherwise? Peter Duniho wrote: > Well, a BufferedReader is a good way to read a line at a time. It would be > trivial to wrap that in an Iterable implementation so that you could use the > syntax above. The Scanner class also provides compact ways to do this, although it's field oriented rather than line oriented. But I have to ask, for what purpose do you want a one-liner? Is this just intellectual curiosity? The normal loop, ignoring exceptions for a heartbeat, is like: BufferedReader reader = ...; for ( String line; (line = reader.readLine()) != null; ) { // do something with line } How much more compact do you want? -- Lew Ceci n'est pas une fenĂȘtre. .___________. |###] | [###| |##/ | *\##| |#/ * | \#| |#----|----#| || | * || |o * | o| |_____|_____| |===========|