wood burning stoves 2.0*
The moose likes I/O and Streams and the fly likes FileInputStream problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "FileInputStream problem " Watch "FileInputStream problem " New topic
Author

FileInputStream problem

AJ sisodia
Greenhorn

Joined: Jan 19, 2005
Posts: 16
PLEASE EXPLAIN LINES MARKED BETWEEN ***** IN THE PROGRM GIVEN BELOW
I GOT THE FIRST PART IN WHICH WE READ FIRST FEW BYTES FROM THE FILE

//CODE
import java.io.*;

class FileInputStreamDemo {
public static void main(String args[]) throws Exception {
int size;
InputStream f = new FileInputStream("C:\\Orahome1\\jdk\\bin\\TwoObservers.java");
System.out.println("Total Available Bytes: " + (size = f.available()));
int n = size/40;
System.out.println("First " + n + " bytes of the file one read() at a time");
for(int i=0; i<n; i++)
System.out.print((char)f.read());
System.out.println("\nStill Available: " + f.available());

***** byte b[] = new byte[n];
if(f.read(b) != n) //WHY ARE WE DOING THIS AND WHAT FOR???
System.err.println("couldn't read " + n + "bytes.");
System.out.println(new String(b, 0, n));*****
System.out.println("\nStill Available: " + f.available());
f.skip(size/2);
System.out.println("\nStill Available: " + f.available());
if(f.read(b,n/2,n/2) != n/2)
System.err.println("couldn't read " + n/2 + "bytes.");
System.out.println(new String(b, 0, n));
System.out.println("\nStill Available: " + f.available());
f.close();

}}

AFTER READING THE FIRST FEW BYTES IS THERE ANY OTHER WAY OF READING THE REMAINING BYTES OTHER THAN THE WAY MENTIONED ABOVE?
Jeremy Tartaglia
Ranch Hand

Joined: Mar 11, 2004
Posts: 62


Line 1: This is creating an array of bytes n deep. Basic simple Java, sometimes written as byte[] b=new byte[n];

Line 2: This line accomplished two tasks. First, you read in as many bytes as possible into b, up to the length which is n. The second part, is if the program could not read n bytes in, it goes to line 3. Otherwise, it skips over it.

Line 3: Reading this line should explain line 2 a bit more. System.err is used instead of System.out just in case you changed where System.out or System.err prints. It's usually smarter to output all errors to System.err.

Line 4: This creates a new string from the byte array b, starting from index 0, and copying at most n bytes. This is listed quite clearly in the Java API

Hope this helps!
rico yu
Greenhorn

Joined: Feb 10, 2006
Posts: 4
the explain is very clearly,thanks
 
 
subject: FileInputStream problem
 
Similar Threads
Is it possible to truncate some data from end of file?
Java nio
how to encrypt data into an image
How to read character stream and byte stream at the same time?
PC Connected to Internet and Internet Connectivity?