Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileInputStream problem

 
AJ sisodia
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the explain is very clearly,thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic