Archive for category Java IO

Using Scanner class to get input from user in java

java.util.Scanner class provides a way to get input from user:

Scanner scanner = new Scanner(System.in);

If input is String:

String string= scanner.nextLine();//to read input as a whole line

or

String string= scanner.next(); // to read single word

To read integers:

int i= scanner.nextInt();

Here is an article helpful on Scanner.

,

Leave a comment

Writing a file in java

Here is the code to write a string to a file in java:

import java.io.*;
class WriteFile {
public static void main(String args[]) {
try{
String s="data to write in file";
File f=new File("a.txt");
FileWriter fwr= new FileWriter(f);
Writer wr= new BufferedWriter(fwr);
wr.write(s);
wr.close();
}
catch(IOException ie) {
System.out.print(ie);
}
catch(Exception e) {
System.out.print(e);
}
}
}

First make a reference to file to which you want to write the data:
File f=new File("a.txt");
Here, in place of .txt, we can use any file extension as .srt,.xml,.doc etc

Then, create a file writer,
FileWriter fwr= new FileWriter(f);

Then, make a writer to write to the file:
Writer wr= new BufferedWriter(fwr);

then, call write function and pass the string:
wr.write(s);
Always remember to close the writer, otherwise it won’t write to the file:
wr.close();

We have to catch the exceptions thrown by the API methods also. To know more about exceptions, go to Java Exceptions

Leave a comment