Sunday, July 29, 2012

Creating a file in Java

Until now, the posts I wrote were on setting up development environment but for the first time I am gonna write something about coding. It's a simple tutorial on how to create files in Java. It's nothing fancy but just a point for me to start and take you into a bit of programming. So let's get started. 

There are many times when you need a file during development may be to write some data (could be a txt or csv or your own format). It's very simple to create a file. You simply need to use the File class from the Java IO. It has many methods and one of them is File.createNewFile().

The steps are: 
  1. Create a File object: 

    File fileToCreate = new File("nameOfFile");
  2. The second step is to create the file:

    fileToCreate.creatNewFile() 
And that's all. Here is example code:


package home.flicker.java.io.file;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * @author flicker
 * Example to create a file with user given name.
 */
public class FileCreation {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter name of File you want to create: ");
    String fileName = scanner.next();
    File fileToCreate = new File(fileName);
    try {
if(fileToCreate.createNewFile()){
       System.out.println("File created!!!");
      }
else{
       System.out.println("Can't create new file as it already exists!!!");
}
    } catch (IOException e) {
System.out.println("Error while creating file!!! " + e.getMessage());
    }
  }
}


Here is a screen-shot of the output:


The example code is pretty simple and self explanatory. Share your issues or confusions. 
I will be posting more on File reading, writing and other file related operations. 


No comments: