Scanner class (java.util
package) ka use ham mostly user se console input lene, ya file se data padhne ke liye karte hain. Ye kaafi flexible hai – alag alag data types ke liye instantly input read kar sakte ho!
nextInt()
, nextLine()
, nextDouble()
, hasNext()
Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(new File("input.txt"));
nextInt()
ke baad agar nextLine()
use karo toh blank line mil sakti hai (kyunki newline consume nahi hota).import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Naam batao: ");
String name = sc.nextLine();
System.out.print("Umra batao: ");
int age = sc.nextInt();
System.out.println("Hello " + name + ", Age: " + age);
sc.close();
}
}
Scanner sc = new Scanner(new File("data.txt"));
while(sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
split()
ka use karo for more control.PrintWriter class (java.io
package) ka use text files, console ya network streams mein formatted data likhne ke liye hota hai. Ye FileWriter ya OutputStream se zyada flexible hai.
println()
or printf()
printf("%s %d", name, age)
import java.io.*;
public class PrintWriterDemo {
public static void main(String[] args) {
try {
PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
pw.println("Hello World!");
pw.printf("Name: %s Age: %d", "Amit", 22);
pw.close();
System.out.println("File written!");
} catch(Exception e) {
e.printStackTrace();
}
}
}
PrintWriter pw = new PrintWriter(System.out, true); // autoFlush on
pw.println("Yeh console par print hoga!");
pw.close();
close()
karo, nahi toh data file mein na jaye.checkError()
ka use karo.Competitive programming ya exams mein aksar user input le ke file me likhna padta hai. Scanner se input lo, PrintWriter se save karo, super easy:
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(new FileWriter("log.txt"));
while(sc.hasNextLine()) {
String line = sc.nextLine();
pw.println(line); // File me save
}
pw.close();
sc.close();