Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2007

Tip: Looking for answers? Try searching our database.

How to detect End-of-File?

Thread view: 
newbie_at_sendmail - 02 Apr 2007 23:11 GMT
Hi,

I'm quite new to java and I have huge problems doing something as simple as reading a file (up to end-of-file).
Can anybody please tell me what I'm doing wrong/is missing? I can't figure it out.

Thanks in advance.

package end_of_file;

import java.lang.String;
import java.io.File;
import java.util.Scanner;
import java.io.IOException;
import java.io.EOFException;
import static java.lang.System.out;

public class this_will_never_work
{
 public static void main(String args[]) throws IOException
 {
   Scanner myScanner =
        new Scanner(new File("c:\\temp\\this_will_never_work.txt"));
   while (true)
   {
     try
     {
       String regel = myScanner.nextLine();
       out.println("Gelezen regel= "+regel);
       throw EOFException;
     } catch (EOFException e) {out.println("Laatste regel gelezen");}
   }
 }
}
Knute Johnson - 02 Apr 2007 23:35 GMT
> Hi,
>
[quoted text clipped - 29 lines]
>   }
> }

I'm not sure that Scanner is the most convenient class or practical
class to use to get data from a random text file.  If the file is some
sort of structured data then it does make some sense.  What type of data
is the file and what are you going to do with it?

import java.io.*;
import java.util.*;

public class test {
    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(new File("test.java"));
        while (s.hasNext())
            System.out.println(s.next());
    }
}

Signature

Knute Johnson
email s/nospam/knute/

Zefria - 03 Apr 2007 02:22 GMT
java.io.BufferedReader is also a possibility. It wraps around a
java.io.FileReader. The code might look something like this:

public void FileReadingMethod(String filename)
{
    BufferedReader br = null;
    String line;
    try
    {
        br = new BufferedReader(new FileReader(filename));
    }
    catch (FileNotFoundException e)
    {
        System.err.println("Requested file was not found!");
        System.exit(1);
    }
    try
    {
        line = br.readLine();
        while (true)
        {
            /////////
            // PROCESSING CODES GOES HERE
            /////////

            // Read the next line. If line==null, that indicates the end of the
file.
            line = br.readLine();
            if (line == null) break;
        }
    }
    catch (IOException e)
    {
        System.err.println("File was found, but an IOError occured!");
        System.exit(2);
    }
}
Esmond Pitt - 03 Apr 2007 02:52 GMT
> java.io.BufferedReader is also a possibility. It wraps around a
> java.io.FileReader. The code might look something like this:
[quoted text clipped - 16 lines]
>         line = br.readLine();
>         while (true)

if (line == null) break; is missing here before the 'while'.

As you have to code the read and the test twice in this style, the loop
is generally written like this:

String line;
while ((line = br.readLine() != null)
{
  // ...
}

or

for (String line; (line = br.readLine()) != null;)
{
  // ...
}
Daniel Gee - 03 Apr 2007 06:17 GMT
Ah, I had forgotten about the possibility of an empty file. I guess
the code is better written as:

try
{
    line = br.readLine();
    while (true)
    {
        if (line == null) break;

        /////////
        // PROCESSING CODES GOES HERE
        /////////

        line = br.readLine();
    }
}
catch(Exception e){...}

As for that "while( (line = br.readLine() != null )" nonsense, the
Python programmer in me knows otherwise.
Gordon Beaton - 03 Apr 2007 06:33 GMT
>     line = br.readLine();
>     while (true)
>     {
>         if (line == null) break;

[...]

> As for that "while( (line = br.readLine() != null )" nonsense, the
> Python programmer in me knows otherwise.

Feel free to ignore the idiom, but at least put the loop condition
where it belongs:

 try {
   line = br.readLine();
   while (line != null) {
     //////
     // PROCESSING CODES GOES HERE
     //////
     line = br.readLine();
   }
 catch (Exception e) {...}

/gordon

--
Lew - 03 Apr 2007 12:42 GMT
> Feel free to ignore the idiom, but at least put the loop condition
> where it belongs:
[quoted text clipped - 8 lines]
>     }
>   catch (Exception e) {...}

or equivalently,

 for ( line = br.readLine(); line != null; line = br.readLine() ) ...

Signature

Lew

Esmond Pitt - 04 Apr 2007 01:44 GMT
> or equivalently,
>
>  for ( line = br.readLine(); line != null; line = br.readLine() ) ...

or equivalently,

  for (String line; (line = br.readline()) != null;) ...
Luc The Perverse - 04 Apr 2007 04:01 GMT
>> or equivalently,
>>
[quoted text clipped - 3 lines]
>
>   for (String line; (line = br.readline()) != null;) ...

or equivalently,

String line;
while((line = br.readline()) != null) . . .

--
LTP

:)
Arne Vajhøj - 04 Apr 2007 02:26 GMT
>>     line = br.readLine();
>>     while (true)
[quoted text clipped - 18 lines]
>     }
>   catch (Exception e) {...}

Two readLine's will never convince me as being a better
solution than one.

Arne
Chris Uppal - 04 Apr 2007 08:27 GMT
> >   try {
> >     line = br.readLine();
[quoted text clipped - 8 lines]
> Two readLine's will never convince me as being a better
> solution than one.

Agreed entirely.  Some people may find the assign-in-the-test idiom not quite
to their taste, but that /is/ a matter of taste, and it is at worst an
established idiom.  But duplication is more than unconventional, it is more
than ugly -- it is /wrong/.

   -- chris
Gordon Beaton - 04 Apr 2007 09:03 GMT
>> Two readLine's will never convince me as being a better
>> solution than one.
[quoted text clipped - 3 lines]
> at worst an established idiom. But duplication is more than
> unconventional, it is more than ugly -- it is /wrong/.

Just to be clear - I'm with both of you on this. My comment was
directed at the *other* bad smell in the earlier post:

 while (true) {
   if (something) break;

   // other stuff
 }

/gordon

--
Daniel Gee - 04 Apr 2007 09:26 GMT
> Agreed entirely.  Some people may find the assign-in-the-test idiom not quite
> to their taste, but that /is/ a matter of taste, and it is at worst an
> established idiom.  But duplication is more than unconventional, it is more
> than ugly -- it is /wrong/.

Ah, well, you see, it's not always a matter of taste. In python you
are strictly not allowed to make an assignment when a boolean test is
being made, such as for the while loop. It's even in the FAQ:
http://www.python.org/doc/faq/general/#why-can-t-i-use-an-assignment-in-an-expression

Anyways, it's just a habit to do it however you do it I guess. All the
options are fairly obvious about what they're doing, so even if others
are reading your code they're very unlikely to be lost in it.
squirrel - 06 Apr 2007 11:21 GMT
> >    line = br.readLine();
> >    while (true)
[quoted text clipped - 22 lines]
>
> --

why not use do...while loop as the following:

  String line = null;
  try {
    if
    do {
      //////
      // PROCESSING CODES GOES HERE
      //////
      line = br.readLine();
    }
    while (line != null);
  catch (Exception e) {...}

of course, the pre-condition is the buffer not empty.
Arne Vajhøj - 04 Apr 2007 02:25 GMT
> As you have to code the read and the test twice in this style, the loop
> is generally written like this:
[quoted text clipped - 11 lines]
>   // ...
> }

I would call the first the standard way of coding it.

Arne
Lew - 04 Apr 2007 03:16 GMT
Esmond Pitt wrote:
>> As you have to code the read and the test twice in this style, the
>> loop is generally written like this:
[quoted text clipped - 11 lines]
>>   // ...
>> }

> I would call the first the standard way of coding it.

The second is handy for limiting the scope of 'line'.

-- Lew
Luc The Perverse - 04 Apr 2007 04:51 GMT
> Esmond Pitt wrote:
>>> As you have to code the read and the test twice in this style, the loop
[quoted text clipped - 5 lines]
>>>   // ...
>>> }

Ah!  How did I miss this???

Now I look like an idiot reposting it

GRRR

Sorry guys (gals notwithstanding) - I will try to contribute more
attentively.

--
LTP

:)
Arne Vajhøj - 05 Apr 2007 02:14 GMT
> Esmond Pitt wrote:
>>> As you have to code the read and the test twice in this style, the
[quoted text clipped - 16 lines]
>
> The second is handy for limiting the scope of 'line'.

I would prefer standard code style over limited scope any day.

Arne
Esmond Pitt - 06 Apr 2007 04:27 GMT
> I would prefer standard code style over limited scope any day.

I would say any time they are in conflict you don't really have anything
you could reasonably describe as being 'standard'.
Arne Vajhøj - 07 Apr 2007 01:13 GMT
>> I would prefer standard code style over limited scope any day.
>
> I would say any time they are in conflict you don't really have anything
> you could reasonably describe as being 'standard'.

Not true.

This is a good example.

The while loop is tha standard way of writing that code
in Java (actually in C# too).

Arne
Esmond Pitt - 07 Apr 2007 05:51 GMT
> The while loop is tha standard way of writing that code
> in Java (actually in C# too).

It depends on what you mean by 'standard'. That's the way I write it
too, but I wouldn't let any 'standard', or even any common practice
which is all that you seem to mean by the word, get in the way of
limiting the scope of a variable if I considered that to be more
important in a particular situation.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.