Sunday, April 8, 2018

How to create a new file in java


Most of the time we stuck in some scenario where we need to create the file or directory by coding in java , Let see how to create file in java from scratch.

Let see the program of creating a file in java 

First we will create a project in java , the project structure is as below


Now lets see the program 


package com.programinjava.filecreation;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileCreatorDemo {

 public static void main(String[] args) throws IOException {

  FileCreatorDemo demo = new FileCreatorDemo();
  //  We need to create a file with Name - temp.txt
  String fileName = "temp.txt";
  //  call createFile Function


  if(demo.createFile(fileName)) {
   System.out.println("File is successefully created");
   String writeThis = " We need to write this in file";
   byte [] b = writeThis.getBytes();
   Files.write(Paths.get(fileName), b);

  }else {
   System.out.println("File is not created ");
  }

 }

 public boolean createFile(String fileName) {

  if(fileName!=null) {
   File f = new File(fileName);
   if(!f.exists())
    try {
     if(f.createNewFile())
      return true;
    } catch (IOException e) {
     e.printStackTrace();
    }
  }else {
   System.out.println("Filename is null");
   return false;
  }
  return false;

 }

}



Explanation :

  • First we are create one file using the new File() of java IO package.
  • then we have used the f.createNewFile() method to create a file .
  • now we need to write something in file for which we have put statement in String and then convert it to bytes.
  • Now as we have bytes we will now use Files.write function to write that statement , this function required the path of the file and the bytes which need to write.
You can download this from FileCreationDemo.zip

If you have any issue , leave us a comment.

Thanks for reading

0 comments:

Post a Comment