-1

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 ?

mattias
  • 2,079
  • 3
  • 20
  • 27
Arnav Das
  • 301
  • 2
  • 5
  • 11
  • You're only reading one character from the System input, which is what gets written to file (you may want to use a `Scanner` for your convenience). – Mena Jun 21 '16 at 15:29
  • @Mena well how should i modify it ? could you suggest a way ? – Arnav Das Jun 21 '16 at 15:32
  • @Mena so read() method just reads one character at a time ? well lf i still want to use read() method for System input, like if i use for or while loop can it be modified ? – Arnav Das Jun 21 '16 at 15:35

1 Answers1

1

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()
Bhaskar
  • 680
  • 7
  • 26