Searching...
Sunday, 4 August 2013

Java I/O package-File/Directory creation

Java I/O package

File Creation


Hi Guys, Welcome to Java I/O package tutorial. Let me explain file/directory creation with a simple example

package com.java.everythingaboutselenium;
import java.io.File;
import java.io.IOException;

public class CreateNewFileExample
{
public static void main( String[] args )
    {
    try {
                File f=new File("c:\\Javafile.txt");
             
                /* This will check whether file Javafile.txt is available or not.
                   If the file is available then f will point to that file, otherwise
                  This line won’t create a new physical file, Just it represents name of the file */
               
               System.out.println(f.exists());
 
  f.createNewfile();
 
  /*This method is used to create a new file */
 
  if (f.exists())
  {
System.out.println("File is created!");
  }
  else
  {
System.out.println("File not created.");
  }
}  

    catch (IOException e) {
     e.printStackTrace();
}
}
}

Output :

false /*As the file JavaFile.txt does not exist*/
File is created /*As now we created a new file using createNewfile method*/

Directory Creation: 

Java File object can be used in the similar manner to represent directory

package com.java.everythingaboutselenium;
import java.io.File;
import java.io.IOException;

public class CreateNewDirExample
{
public static void main( String[] args )
    {
    try {
File d=new File("c:\\Javadirectory.txt");
System.out.println(d.exists());
/* This will return true if directory already exists, otherwise it returns false */

d.mkdir();
if (d.exists())
{
System.out.println("Directory is created!");
}
else
{
System.out.println("Directory not created");
}
}
catch (IOException e) {
     e.printStackTrace();
}
}
}

1 comments:

  1. I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
    Data science Course Training in Chennai | No.1 Data Science Training in Chennai
    RPA Course Training in Chennai | No.1 RPA Training in Chennai

    ReplyDelete

 
Back to top!