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();
}
}
}
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();
}
}
}