by Dinesh Thakur

Here is the Java Example for Write Data to a File Using Scanner:

import java.util.Scanner;

import java.io.*;
public class WriteFileUsingScanner
{
              public static void main(String[] args)throws Exception
       {
              String p=setpath();
              write(p);
              System.out.println("\n\n\t\t1 File Created Successfully");
        }
                  static String setpath()
            {
                     Scanner read =new Scanner(System.in);
                     String path;
                     System.out.println("Enter the Path You want to Set \n\t");
                     return read.nextLine();
            }
                     static void write(String path)throws Exception
                 {
                        Scanner read =new Scanner(System.in);
                        FileOutputStream fos=new FileOutputStream(path);
                        System.out.println("\n\t\tEnter character  ('y') to stop writing.\n\n");
                        int ch;
                        String data;
                        byte b[];
                        boolean flag=true;
                        byte eof=(char)('y');
                        while(true)
                               {
                                  data=read.nextLine();
                                  b=data.getBytes();
                                  for(int i=0;i<b.length;i++)
                                      {
                                          if(b[i]==eof)
                                             {
                                                 flag=false;
                                                 break;
                                             }
                                                  fos.write(b[i]);
                                       }
                                             if(flag==false)
                                                break;
                                               fos.write((byte)('\n'));
                                 }
                                               fos.close();
                     }
}

Write Data to a File Using Scanner