15 How to load data dynamically from keyword using java.io.BufferdReader in Java?

Able to Read Data From:
1) Reading from the Keyboard
2) Reading from the File
3)Reading from the Socket

How to read the data from the keyboard using BufferedReader

If BufferedReader wants to communicate with keyboard then using InputStreamReader.

For Ex:
BRDemo.java

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class BRDemo{
public static void main(String[] args) throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);

//Reading String Data
System.out.println("Enter Some String Data: ");
String s = br.readLine();
System.out.println("\n String:"+s);

//Reading Integer Data
System.out.println("Enter Some Integer Data: ");
int s1 = br.read();
System.out.println("\n Integer:"+s1);

}
}

Output: 



How to read the data from the file using BufferedReader

If BufferedReader wants to communicate with files then using FileReader.

For Ex: In this Program I am writing the data into the File.
BRDemo.java

import java.io.FileWriter;
import java.io.IOException;
public class BRDemo{

public static void main(String[] args)
throws IOException{
FileWriter fw=new FileWriter("ca.text");
fw.write(new char[]{'d','a','d'});
fw.flush();
}
}

Output: 


Now using the BufferedReader Reading the file data.

For Ex: In this Program I am reading the data  from the File "ca.text".

BRDemo.java

import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class BRDemo{

public static void main(String[] args)
throws IOException{
FileReader fr= new FileReader("ca.text");
BufferedReader br=new BufferedReader(fr);
String s= br.readLine();
System.out.println("\n\n Data in to file: "+s);
}
}

Output: 

Now suppose we want to add the data of the file using StringTokenizer then
Suppose I have data in file 10 20 30 40 in string format and I want to add this data.

BRDemo.java

import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;

public class BRDemo{

public static void main(String[] args)
throws IOException{
FileReader fr= new FileReader("ca.text");
BufferedReader br=new BufferedReader(fr);
String s= br.readLine();
System.out.println("\n\n Data in to file: "+s);

int count=0;
StringTokenizer st= new StringTokenizer(s," ");

while( st.hasMoreTokens() ){
count = count + Integer.parseInt( st.nextToken() );
}

System.out.println("\n\n Sum: "+count);

}
}

Output:

Previous
Next Post »