Input and Output in Java
Input and Output in Java
- We have 2 types Input and Output streams in Java
- Byte IO Streams
- Character IO Streams
- Example for the Byte IO Streams are FileInputStream and FilerOutputStream
- Example for the Character IO Streams are FileReader and FileWriter
- We have three types of Standard IO redirectors
- Input – System.in – To accept the input
- Output – System.out – To print the output on console
- Error – System.err – To print the Error information to console.
- For reading input from the console Scanner class will help. It is belongs to the until package of Java.
Example:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int x=s.nextInt();
System.out.println(x);
System.out.println("Enter a Strinng");
String str = s.next();
System.out.println(str);
}
}
Java Input and Output Example:
Example:
import java.util.*;
public class Main
{
public static void main(String[] args) {
FileInputStream fi = null;
FileOutputSream os = null;
try{
in = new FileInputStream("one.txt");
os = new FileOutputSream("two.txt");
int c;
while((c=in.read())!=-1){
out.write(c);
}
finally{
if(in != null){
in.close();
}
if(os != null){
os.close();
}
}
}
}
Click Here-> Get Java Training with Real-time Projects