Arnav Das Arnav Das - 5 months ago 17
Java Question

Why am i not able to print the whole character as i have entered it?

As an amateur java learner i was trying out different combinations of java file and I/O methods, as i tried out this code where i wanted to print whatever i entered into the file

tom.txt
through my code(i understand what i want could be easily done by using other methods), my code was this :

import java.io.*;
public class Dhoom3
{
public static void main(String[] args) throws IOException, NullPointerException
{
FileWriter b = new FileWriter(new File("tom.txt"));
System.out.println(" enter whatever : ");
b.write(System.in.read());
b.flush();
System.out.println("the printed characters are");
FileInputStream r = new FileInputStream("tom.txt");
BufferedInputStream k = new BufferedInputStream(r);
int g;
while((g = k.read())!= -1)
{
System.out.println((char)g);
}
}

}


my output was this :

enter whatever :
stack
the printed characters are
s


where did i commit my mistake,or where should i modify my program ?, Basically why is my code only printing the first character ?

Answer

Your error is using

System.in.read()

to read input.

System.in.read only reads one byte of input.

The better alternative to this is to use Scanners. Scanners can scan multiple bytes of information, so they are better for what you are doing.

To fix your code:

1) Create a new Scanner object like so:

Scanner scanner = new Scanner(System.in);

2) Replace System.in.read with:

scanner.next()
Comments