Home > Java > Java Program to read from a file using FileInputStream and use available(), skip() to go through bytes – Q38

Java Program to read from a file using FileInputStream and use available(), skip() to go through bytes – Q38

January 19, 2009 Leave a comment Go to comments

Q38: Java Program to read from a file using FileInputStream and use available(),skip() to go through bytes. Read ¼ n bytes on console, next ¼ n bytes on a byte array , and next ¼ n bytes skip and next ¼ n bytes again print it on console.

import java.io.*;

class FILE_AV_SK{
	public static void main(String args[]) throws IOException{
		int size;
		InputStream f=new FileInputStream("tax.java");
		
		size = f.available();
		System.out.println("Total Available Bytes:" + size);
		
		int n=size/4;
		System.out.println("(1). First "+ n + " bytes of the file Displaying to Console");
		for(int i=0;i<n;i++)
			System.out.print((char) f.read());
			
		System.out.println("\nStill Available: "+ f.available());
		System.out.println("(2). Reading the next " + n +" and Storing to Byte Array.");
		
		byte b[] = new byte[n];
		for(int i=0; i<n; i++)
			b[i] = (byte) f.read();
		
		System.out.println("\nStill Available: "+(size = f.available()));
		System.out.println("(3). Skipping half of remaining bytes with skip()");
		f.skip(n);
		
		System.out.println("Still Available: "+f.available());
		System.out.println("(4). Last "+ n + " bytes of the file Displaying to Console");
		for(int i=0;i<n;i++)
			System.out.print((char) f.read());
		
		f.close();
	}
}

… from College notes (BCA/MCA assignments):


Advertisement
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: