Write a java program to create a file of given name and directory and copy a file named myjava.java available at desktop. (IGNOU assignment mcs024)



import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

class Myfile
{
 public static void main(String args[])
 {
  String newFileName = "";
  System.out.println("Enter the file name : ");
  Scanner scan = new Scanner(System.in);
  newFileName = scan.next();
  File newFile = new File(newFileName);
  
//Creating a new file with the name and folder path given by the user as input
  try {
   newFile.createNewFile();
  } catch (IOException e) {
  System.out.println(e);
  }
  
// Now copy myjava.java available at desktop and paste its content in the new file created by us
  
  try{
  String desktopFilePath =System.getProperty("user.home") + "\\"+"Desktop\\myjava.java";
  File desktopFile = new File(desktopFilePath);
  FileInputStream fis = new FileInputStream(desktopFile);
  BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 
  FileWriter fstream = new FileWriter(newFile, true);
  BufferedWriter out = new BufferedWriter(fstream);
 
  String aLine = null;
  while ((aLine = in.readLine()) != null) {
   //Coping the content of myjava.java and pasting in the new file
   out.write(aLine);
   out.newLine();
                        System.out.println("New file successfully created with copied content of myjava.java");
  }
   in.close(); 
  out.close(); 
  } catch (IOException e) {
  System.out.println(e);
  }
 }
}

Save this program file as Myfile.java

Now create myjava.java file on desktop with some random text. and then run the Myfile.java file.

OUTPUT :-

javac Myfile.java
java Myfile
Enter the file name :
d:/testing.txt
New file successfully created with copied content of myjava.java




Share on Google Plus

About Unknown

Hrishabh Sharma is the founder of an IT firm "Chanakya IT Solutions" that offers a variety of software,website,mobile-app solutions. He has more than 7 years of experience in software and web development. You can contact him at FACEBOOK or Send email at hrs.king@yahoo.in
    Blogger Comment
    Facebook Comment

1 comments: