Why Android app DOES NOT run on Java Virtual Machine!

I had a misconception for like years that as we write code in java for android application so there must be an JVM [just like on J2ME mobiles ] in underline android Operating System but actually I was actually wrong. So I have written a little bit on the differences.
Its true that for most of the android development we use java and we need to compile it like other java development. When in our IDE we hit compile button it also generates Java byte-code files which will be better understood if I say .class files. But later on these .class files get compressed and get converted into a single byte code file using DX converter which usually known as classes.dex. Then this dex filles packaged with other application resources and become a .apk file. We can install this .apk file in the devices. When we run this application, JRE does not run the .dex file instead Dalvik Virtual Machine executes that dex bit codes.
Since JVM and Delvik are turing complete, so basically end of the day they do the same things. But it has internal differences. The key difference is that JVM is stack-based, while Dalvik is register based.
I think it will be better if we remind the example of stack based addition and register based addition.
In an stack stack based addition when we need to add a set of numbers we put all of them into a stack then we would pop top two and add them up then again we would push that summation in the stack and we will pop two and sum them up and we will repeat this process until the stack is empty. So it takes minimal process to implement stack based VM because only 2 register can do it. Which is very important for JVM because it supports a wide range of devices.

On the other hand register based system it requires to tell the explicit memory location in the memory if we want it to add. But the average register instruction is larger than an average stack instruction. once we tell them the location explicitly we don’t need to go through all this over head of push, pop which helps android to run on slow CPU and less RAM. Additionally in register based virtual machine few optimization can be done which on low battery consumption. DVM has been designed so that a device can run multiple instances of the VM efficiently.

Adding animation on character movement using Libgdx

reviously, we have talked about making a character. But our character was lifeless. It was like moving image left or right. Now it is time to add animation to our character bob so that it look more like a character who has life. Most importantly this time I am writing my own code. This time I am not explaining other’s code in my own word like my previous 2 libgdx blog.

First thing we got to do is, we have to make a sprite-sheet.

We have to store it in the asset directory of android.

Now to contemplate where actually we were rendering our character bob? We have done it in WorldRenderer.java. It has a render() method which is responsible for decoration of the environment.

public void render() {
spriteBatch.begin();
drawBlocks();
drawBob();
spriteBatch.end();

if (debug)
drawDebug();
}

we are more interested about the character animation today so we will be rewriting our drawBob() method today. But before that we must load our textures first in loadTextures() method which is being called in the constructor of this class. What actually we need to load here? We need to load our sprite image. Then we need to divide and split it into frames into a 1D array and then we have to make Animation object using this Array and we also need to define the time each frame will consume. Thats it.

	private static final int        FRAME_COLS = 6;      
    private static final int        FRAME_ROWS = 5;        
    Animation                       walkAnimation;          
    Texture                         walkSheet;              
    TextureRegion[]                 walkFrames;             
    TextureRegion                   currentFrame;           

    float stateTime;                                        

	private void loadTextures() {
		walkSheet = new  Texture(Gdx.files.internal("animation_sheet.png"));
		TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth() / 
				FRAME_COLS, walkSheet.getHeight() / FRAME_ROWS);
		walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
        int index = 0;
        for (int i = 0; i < FRAME_ROWS; i++) {
                for (int j = 0; j < FRAME_COLS; j++) {
                        walkFrames[index++] = tmp[i][j];
                }
        }
        walkAnimation = new Animation(0.025f, walkFrames);

        stateTime = 0f;

        bobTexture = new  Texture(Gdx.files.internal("images/bob.png"));
        blockTexture = new Texture(Gdx.files.internal("images/block.png"));
	}

As I was saying, we need to move to our main focused function drawBob(). To access the sprite frames we need to access to the frames via time elapsed. So we need to keep updating stateTimewith a delta otherwise the same frame will keep appearing. Gdx.graphics.getDeltaTime() returns the time passed since the last call to render() in seconds. So basically I was explaining this code.

private void drawBob() {
	Bob bob = world.getBob();
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, facex*Bob.SIZE * ppuX, Bob.SIZE * ppuY);
}

Bingo! Sprite works. BUT! This is odd because bob is animating its run state all the time even when he is not running, it need to be fixed, right? Actually we have been preparing for this moment from the first day. Remember we are keeping an enum to keep the current state of bob and using controller we are updating bob’s state. So here it will only need a if else condition to check what is the current state of bob. Is he running? Or another word, is user pressing arrow keys? If yes then show this animation:

if (bob.state==bob.state.WALKING){
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, Bob.SIZE * ppuX, Bob.SIZE * ppuY);

}

and if he is idle show that old static image.

else if(bob.state==bob.state.IDLE){
			spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY,Bob.SIZE * ppuX, Bob.SIZE * ppuY);
		}

We are good now, aren’t we? Yes we have improved a lot. But still when we move left the bob face in one direction thats what we want so no complain but when we move right bob keep his face to that old direction again! Thats stupid, is not it? So we need to flip the direction of our sprite and image. It is not hard at all. It requires trick. if add negative to the size of the image it will flip the image in X axis. So lets put this function together:

private void drawBob() {
		Bob bob = world.getBob();

		int facex=1;
		if(bob.facingLeft){
			facex=-1;
		}

		if (bob.state==bob.state.WALKING){
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, facex*Bob.SIZE * ppuX, Bob.SIZE * ppuY);

		}
		else if(bob.state==bob.state.IDLE){
			spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, facex* Bob.SIZE * ppuX, Bob.SIZE * ppuY);
		}

			//spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, Bob.SIZE * ppuX, Bob.SIZE * ppuY);

	}

We are basically done!

Now put the hole class together:

package com.me.mygdxgame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;

public class WorldRenderer {

 private World world;
 private OrthographicCamera cam;

 /** for debug rendering **/
 ShapeRenderer debugRenderer = new ShapeRenderer();

 public WorldRenderer(World world) {
  this.world = world;
  this.cam = new OrthographicCamera(10, 7);
  this.cam.position.set(5, 3.5f, 0);
  this.cam.update();

  spriteBatch = new SpriteBatch();
  loadTextures();
 }

	private static final float CAMERA_WIDTH = 10f;
	private static final float CAMERA_HEIGHT = 7f;
	private SpriteBatch spriteBatch;
	private boolean debug = false;
	private int width;
	private int height;
	private float ppuX;	// pixels per unit on the X axis
	private float ppuY;	// pixels per unit on the Y axis
	public void setSize (int w, int h) {
		this.width = w;
		this.height = h;
		ppuX = (float)width / CAMERA_WIDTH;
		ppuY = (float)height / CAMERA_HEIGHT;
	}
   private void drawBlocks() {

	          for (Block block : world.getBlocks()) {
	              spriteBatch.draw(blockTexture, block.position.x * ppuX, block.position.y * ppuY, Block.SIZE * ppuX, Block.SIZE * ppuY);
	          }

	      }

/** Textures **/
	private Texture bobTexture;
	private Texture blockTexture;

	private static final int        FRAME_COLS = 6;      
    private static final int        FRAME_ROWS = 5;        
    Animation                       walkAnimation;          
    Texture                         walkSheet;              
    TextureRegion[]                 walkFrames;             
    TextureRegion                   currentFrame;           

    float stateTime;                                        

	private void loadTextures() {
		walkSheet = new  Texture(Gdx.files.internal("animation_sheet.png"));
		TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth() / 
				FRAME_COLS, walkSheet.getHeight() / FRAME_ROWS);
		walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
        int index = 0;
        for (int i = 0; i < FRAME_ROWS; i++) {
                for (int j = 0; j < FRAME_COLS; j++) {
                        walkFrames[index++] = tmp[i][j];
                }
        }
        walkAnimation = new Animation(0.025f, walkFrames);

        stateTime = 0f;

        bobTexture = new  Texture(Gdx.files.internal("images/bob.png"));
        blockTexture = new Texture(Gdx.files.internal("images/block.png"));
	}
	public void render() {
		 spriteBatch.begin();
				drawBlocks();
				drawBob();
		 spriteBatch.end();

			if (debug)
				drawDebug();
		  }
	private void drawBob() {
		Bob bob = world.getBob();

		int facex=1;
		if(bob.facingLeft){
			facex=-1;
		}

		if (bob.state==bob.state.WALKING){
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, facex*Bob.SIZE * ppuX, Bob.SIZE * ppuY);

		}
		else if(bob.state==bob.state.IDLE){
			spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, facex* Bob.SIZE * ppuX, Bob.SIZE * ppuY);
		}

			//spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, Bob.SIZE * ppuX, Bob.SIZE * ppuY);

	}
	private void drawDebug() {
		// render blocks
		debugRenderer.setProjectionMatrix(cam.combined);
		debugRenderer.begin(ShapeType.Line);
		for (Block block : world.getBlocks()) {
			Rectangle rect = block.bounds;
			float x1 = block.position.x + rect.x;
			float y1 = block.position.y + rect.y;
			debugRenderer.setColor(new Color(1, 0, 0, 1));
			debugRenderer.rect(x1, y1, rect.width, rect.height);
		}
		// render Bob
		Bob bob = world.getBob();
		Rectangle rect = bob.bounds;
		float x1 = bob.position.x + rect.x;
		float y1 = bob.position.y + rect.y;
		debugRenderer.setColor(new Color(0, 1, 0, 1));
		debugRenderer.rect(x1, y1, rect.width, rect.height);
		debugRenderer.end();
	}
 }

How to create simple menu in libgdx

Actually making menu using libgdx is pretty easy, but most probably because of the lack of tutorial or (proper SEO) initially it took me a little more time then usual to make it done, It has become easier for me when I have a look at their test cases provided. Let me share a simplified code with you guys. Here in this tutorial we will write code for a button that starts the game.

In our main method we have to run a new instance of LwjglApplication class which requires an ApplicationListener to launch. So we need to implement ApplicationListener for sure. As the Game class provides few extra benefit like setting which screen to show up and things. So in this blog I will be extending Game class. Game class has a setScreen method just changing it decides which method will be shown in the screen. We want to take advantage of it in future when the button will get pressed so I am sending a self instance of this class.

//MainMenuGame.java

package com.sadafnoor.MainMenu;
 
import com.badlogic.gdx.Game;
 
public class MainMenuGame extends Game {
@Override
public void create() {
setScreen(new MenuScreen(this));
}
}

Now we will be writing the code we are interested about. We will extend the screen class as it is required for setScreen(). We need to create a Stage to add our button which handles the viewing region and at the same time takes care of the input actions so we need to send it to input process as well.

stage = new Stage();
Gdx.input.setInputProcessor(stage);

We need to define the skin of our button which is basically the background color, fonts and so on.

BitmapFont bfont=new BitmapFont();
bfont.scale(1);
skin.add("default",bfont);

Now we need to define the style of our button, which is TextButtonStyle. Here will get a lot of options to deal with. we can define what colors will it take when the mouse is over it, when the button is pressed and so on. and then finally we can create our TextButtion. Then we can set the position of it and add it to the stage.

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;

public class MenuScreen implements Screen {
	Skin skin;
	Stage stage;
	SpriteBatch batch;

	Game g;
	public MenuScreen(Game g){
		create();
		this.g=g;
	}

	public MenuScreen(){
		create();
	}
	public void create(){
		batch = new SpriteBatch();
		stage = new Stage();
		Gdx.input.setInputProcessor(stage);

		// A skin can be loaded via JSON or defined programmatically, either is fine. Using a skin is optional but strongly
		// recommended solely for the convenience of getting a texture, region, etc as a drawable, tinted drawable, etc.
		skin = new Skin();
		// Generate a 1x1 white texture and store it in the skin named "white".
		Pixmap pixmap = new Pixmap(100, 100, Format.RGBA8888);
		pixmap.setColor(Color.GREEN);
		pixmap.fill();

		skin.add("white", new Texture(pixmap));

		// Store the default libgdx font under the name "default".
		BitmapFont bfont=new BitmapFont();
		bfont.scale(1);
		skin.add("default",bfont);

		// Configure a TextButtonStyle and name it "default". Skin resources are stored by type, so this doesn't overwrite the font.
		TextButtonStyle textButtonStyle = new TextButtonStyle();
		textButtonStyle.up = skin.newDrawable("white", Color.DARK_GRAY);
		textButtonStyle.down = skin.newDrawable("white", Color.DARK_GRAY);
		textButtonStyle.checked = skin.newDrawable("white", Color.BLUE);
		textButtonStyle.over = skin.newDrawable("white", Color.LIGHT_GRAY);

		textButtonStyle.font = skin.getFont("default");

		skin.add("default", textButtonStyle);

		// Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
		final TextButton textButton=new TextButton("PLAY",textButtonStyle);
		textButton.setPosition(200, 200);
		stage.addActor(textButton);
		stage.addActor(textButton);
		stage.addActor(textButton);

	}

	public void render (float delta) {
		Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
		stage.draw();
		Table.drawDebug(stage);
	}

	@Override
	public void resize (int width, int height) {
		stage.setViewport(width, height, false);
	}

	@Override
	public void dispose () {
		stage.dispose();
		skin.dispose();
	}

	@Override
	public void show() {
		// TODO Auto-generated method stub

	}

	@Override
	public void hide() {
		// TODO Auto-generated method stub

	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub

	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub

	}
}

Now we will add callback function. When the key is pressed a callback function of addaction will get triggered and via our previously passed game we will change setScreen.

textButton.addListener(new ChangeListener() {
			public void changed (ChangeEvent event, Actor actor) {
				//System.out.println("Clicked! Is checked: " + button.isChecked());
				textButton.setText("Starting new game");
				g.setScreen( new GameScreen());

			}
		});

Altogether:

[java] “Why this blank Scanner sh*t after each time of taking int or double as input?”

Well, by using java.util.Scanner we can take input from the user, it can be String, it can be integer, it can be double, even it can be a line!

to use java util.Scanner, we first import java.util.* package, then we declare an object of Scanner class:

Scanner sc = new Scanner (System.in);

Since System.in is an input stream, above declared Scanner will takes all necessary inputs from its input streams and System.in let the user give input streams through the system (maybe keyboard).

Various types of inputs can be taken as i have mentioned, can be taken via various next methods:

For example:

next() method is used to take input a word, it starts taking input from the streams and does not not stop until it spots character  a ‘ ‘ (space)!

Example: if the given input of the user is: “yo man”
then next() method will return “yo “, cause, after yo it spots a space ” ” and it refrains from taking any other inputs but in input stream still it has “man”  left next to “yo “, so if we again let next() method get called, then as input stream already has streams, so that next() won’t ask the user to give another input but it would take from the next input stream and so it would return “man” !

nextLine() takes input from the user until it reach an Enter. We have learned that <Enter> is nothing but a spacial character.

Example: users given input is: “yo man” and then press Enter
“How are you” and then press Enter
then nextLine() method will only return “yo man”, cause, after “yo man” it spotted an <Enter> and it refrains from taking any other inputs but in its input stream “How are you <Enter>” is still left!

nextInt() method takes integer inputs from the use and suppose now we call nextInt() method then it will start taking inputs from input stream which was left  before (i mean “How are you <Enter>”) and it would fail to get an Integer so
java.util.InputMismatchException will get thrown.

Now we will see a practical problem that we face due to this sort of thing:

import java.util.*;
public class Student{
Scanner sc=new Scanner(System.in);
System.out.print("Serial no: ");
int Serial =sc.nextInt(); //1st input from the user
System.out.print("Name: ");
String Name = sc.nextLine(); //won't ask the user to give an input
}
}

Why? Why? Why?
At the time when user gives an Integer when “Serial no: ” is asked, the user presses an integer number and then <Enter>.
nextInt() method returns that number and int Serial variable stores that intiger with no difficulty but in input stream <Enter> remains so at the time when nextLine() is being called (at the time when user is asked to give the “Name: ” ) it takes that <Enter> as a input from the input stream so user does not get any chance to enter the name.

Giving a blank sc.nextLine() after each sc.nextInt() can be a solution for this problem as String can hold anything.

System.out.print("Serial no: ");
int Serial =sc.nextInt(); /*user inputs a number and then presses <Enter> and int Serial stores only the number not that extra <Enter>*/
sc.nextLine(); /* it takes extra <Enter> */
System.out.print("Name: ");
String Name = sc.nextLine();

I think this blog post could be dedicated to a Friend with “Whys”, Fahim Bakhtiar, unlike any element of my so called GoodStudent class 😛 who has an unlimited amount of Wh-Questions to ask in his mind. And most probably I also fear what he would ask again regarding this issue where i will get stumbled miserably 😛 but he is always welcome as always! All the best to him!

Disclaimer: This is what i have assumed about Scanner class. Correct me if i am wrong! Suggest me good articles about this Scanner as i have got nothing.

[java] FileInputStream and Reading line by line:

The computer that we are using right now is digital electronic, it is digital because all the information inside it is represented by streams of numbers, more specifically binary numbers. From the perspective of Computer every single file is nothing but a stream of binary numbers. Still now sometimes i stare at my computer and think what not we are making it to do so but it knows nothing more than 0 and 1?  WTF! (Well, That’s Fantastic!)

Before dealing with FileInputStream first of all we have to know what FileInputStream really is.

FileInputIstream is basically a child class of InputStream. It obtains input bytes from a file in a file system. Stream classes basically deal with binary datas and in binary there is no such thing as a “line” so FileInputStream does not have any method which is related with lines.

Our objective is to read from a file line by line using FileInputStream.

First of all it’s in a different not included in java.lang package so if we will use FileInputStream we need to import java.io.* at the beginning of the class.

Scanner or BufferedReader has methods to work with lines so if we can can somehow scan/read Streams through Scanneror BufferedReader, then we can read them line by line using nextLine() or readLine() method.

Constructor Summary of Scanner
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
more…

Scanner does give us opportunity to pass a InputStream through its constructor.

Now, we need to think of a way to make an connection our given file and java.

Constructor of  FileInputStream 
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

 throws FileNotFoundException
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

throws FileNotFoundException

From the summary of the constructor of FileInputStream, we can easily guess  at least two way to make this linkage through the constractor:

1. FileInputStream(String name)
2. FileInputStream(File file)

1. FileInputStream(String name): i think this is the most straight forward way to do this thing. If the file we want to read and our file which we want to to read line by line are at the same directory then we can just write that files name and extension as name constractor and as this constractor throws FileNotFoundException so we also need to handle that exception.

Example: if we want to read a file named “sample.txt” then we would write:

try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt" );
}
catch (FileNotFoundException e){
System.out.println(e);

But if file which we want to to read line by line are not at the same directory then we have to write that files directory briefly and we have to use double ‘//’ in place of single ‘/’ (FYI: as ‘/’ is a escape character and you can’t store a single ‘/’ in a character veritable). Example: if we want to read a file named “sample.txt” which is located at the directory of “C:\Documents and Settings\User\Desktop\sample.txt”, then you have to write:

FileInputStream fileInStreamObj = new FileInputStream("C:\\Documents and Settings\\User\\Desktop\\sample.txt" );

try blocks confines the scope of variables, so we can put this previous piece of code inside same try  block.

Combinig all the pieces:

import java.io.*;
import java.util.Scanner;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt" );
InputStream inStreamObject = ((InputStream) fileInStreamObj);
Scanner sc = new Scanner( inStreamObject );
String input = sc.nextLine();
System.out.println(input);
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}

2. FileInputStream(File file): If we want to use this contractor, first of all we need to define file location with an object of File and then let it go through with FileInputStreams constractor and this constractor also throws FileNotFoundException so we also need to handle that exception.:

try{
File fileObject = new File("sample.txt" );
FileInputStream fileInStreamObj = new FileInputStream(fileObject);
}
catch (FileNotFoundException e){
System.out.println(e);
}

Now we need to convert this FileInputStream into InputStream, but they are  in the same tree so we can cast them. So here we go:


InputStream inStreamObject = (InputStream) fileInStreamObj
Scanner sc = new Scanner(  inStreamObject );
String input = sc.nextLine();

combining all peaces:

import java.io.*;
import java.util.Scanner;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
File fileObject = new File("sample.txt" );
FileInputStream fileInStreamObj = new FileInputStream(fileObject);
InputStream inStreamObject = (InputStream) fileInStreamObj;
Scanner sc = new Scanner( inStreamObject );
String input = sc.nextLine();
System.out.println(input);
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}



we can also do similar thing using BufferedReader:

Constructor Summary of BufferedReader
BufferedReader(Reader in)
Create a buffering character-input stream that uses a default-sized input buffer.
more…

So BufferedReader can take Reader as constructor.

Now we have to convert FileInputStream into Reader or any of its child class.

Constructor Summary of InputStreamReader extends Reader
InputStreamReader(InputStream in)
Create an InputStreamReader that uses the default charset.
more…

InputStreamReader can take  FileInputStream and its in the the same tree of Reader so we can cast any InputStreamReader object into Reader.
ReadLine() method of BufferedReader throws IOException, so we also need to handle that exception.
so,
try{
InputStreamReader inStreamReaderObject = new InputStreamReader(fileInStreamObj);
BufferedReader br = new BufferedReader( (Reader) inStreamReaderObject );
String input = br.readLine();
}
catch(IOException e){
System.out.println(e);
}

combinig previous pieces:

import java.io.*;
public class ReadALineUsingFileInputStream {
public static void main (String [] args){
try{
FileInputStream fileInStreamObj = new FileInputStream("sample.txt");
try{InputStreamReader inStreamReaderObject = new InputStreamReader(fileInStreamObj);
BufferedReader br = new BufferedReader( (Reader) inStreamReaderObject );
String input = br.readLine();
System.out.println(input);
}
catch(IOException e){
System.out.println(e);
}
}
catch (FileNotFoundException e){
System.out.println(e);
}
}
}

Hurrah, now we know how to read a line using FileInputStream. Now using a loop until Scanner hasNext()  or BufferedReader’s readLine() method returns a null!