File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to find end of file in java

 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends,

How to find end of file(EOF) using java?
is there any key by which we can end a file after writing?

Shubhada
 
Peter Chase
Ranch Hand
Posts: 1970
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not quite sure what you want.

If you want to know how many bytes are in the file, then File.length() gives you that.

If you want to write at the end of the file, then FileWriter and FileOutputStream both have constructors that allow you to ask to append to the file. Similarly, you can seek() to the end of a RandomAccessFile, then write to it.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And if you're reading a file, the input stream or reader will tell you when you've hit the end. This kind of thing is very common for reading text files one line at a time:

See how the loop stops - or never starts - when the file is at end?

Actually it's more common to tighten this up a bit with some nifty Java syntax:

The assignment clause "line = reader.readLine()" not only loads the variable line, but it's also an expression with a return value, the same variable. So we can set line and test it for null all in one shot.

Streams work a differently - they report the number of bytes actually read by a read() method, and 0 means end of file.

Does that work for you?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Shubhada]: is there any key by which we can end a file after writing?

Generally you just need to close() the FileWriter or FileOutputStream or whatever you're writing the file with, when you're done writing. That's all.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Stan]: Streams work a differently - they report the number of bytes actually read by a read() method, and 0 means end of file.

End of file is indicated by -1. This is used for both InputStreams and Readers, at least for the read() methods. BufferedReader's readLine() returns a String which may indicate EOF with a null, but most of the other read methods return an int which may be -1 to indicate EOF.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, good catch. -1 it is.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic