In Java Write a program that reads a file that contains only
In Java:
Write a program that reads a file that contains only one line; output all characters, one character per line.
Solution
import java.io.BufferedReader;
import java.io.FileReader; // importing filereader
import java.io.IOException; // importing file io exceptions
public class readChar {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(\"sample.txt\")); // reading file
while ((sCurrentLine = br.readLine()) != null) { // rading line by line
String s = sCurrentLine; // storing line string name s
for (int i = 0; i < s.length(); i++) { // upto string length it displayes charat each index position
System.out.println(s.charAt(i));
}
}
} catch (IOException e) {
e.printStackTrace(); // catch exception
} finally {
try {
if (br != null)br.close(); // closing buffer
} catch (IOException ex) {
ex.printStackTrace();// printing exceptions
}
}
}
}
/********** out file******
fileName:sample.txt
file contains \"Hello world\"
*/
