You are here: Home / Topics / Program to read data from keyboard and write it to the file using FileOutputStream in Java

Program to read data from keyboard and write it to the file using FileOutputStream in Java

Filed under: Java on 2023-10-25 06:52:06

// Program to read data from keyboard and write it to the file using FileOutputStream.

import java.io.*;

class FileOutputStreamDemo
{
public static void main( String args[ ] ) throws 
    IOException
{
 // attach keyboard to DataInputStream
 DataInputStream dis = new DataInputStream( System.in );
 
 // attach file to FileOutputStream
 FileOutputStream fos = new FileOutputStream( "file1.txt" );
 
 System.out.println("Enter string($ to end): ");
 char ch;
 
 // read character from dis into ch and write them into fos.
 while( (ch=(char)dis.read()) != '$' )
 {
  fos.write(ch);
 }
 
 // close the file.
 fos.close();
}
}


Output:

Enter string($ to end): 
Be The Java Developer

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.