Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses
Showing posts with label Streams and Files. Show all posts
Showing posts with label Streams and Files. Show all posts

StringTokenizer class in Java

Program to demonstrate StringTokenizer class in Java

import java.util.StringTokenizer;

public class StringTokenizerDemo {

 public static void main(String[] args) {

  System.out.println("Using , and = as delimiter ..... ");
  String input = "First Name=Dinesh," +
           "Last Name=Varyani," +
           "Blog Name=Learn Java by Examples," +
           "Blog Url=www.hubberspot.com";

  StringTokenizer stringTokenizer = new StringTokenizer(input,"=,");

  while(stringTokenizer.hasMoreElements()) {
   String info = stringTokenizer.nextToken();
   String description = stringTokenizer.nextToken();
   System.out.println(info + " : " + description);
  }

  System.out.println();
  System.out.println("Using default delimiter which is whitespace ... ");

  input = "FirstName Dinesh " +
    "LastName Varyani " +
    "BlogName LearnJavaByExamples " +
    "BlogUrl www.hubberspot.com";

  stringTokenizer = new StringTokenizer(input);

  while(stringTokenizer.hasMoreElements()) {
   String info = stringTokenizer.nextToken();
   String description = stringTokenizer.nextToken();
   System.out.println(info + " : " + description);
  }
 }
}



Output of the program : 

 

How to Write an XML file through a simple Java program ?.

Program to demonstrate how to Write an XML file in Java.

1. Create a simple POJO class whose properties needs to be stored in XML file.

package com.hubberspot.xml.writer;

public class Customer {

 private int customerId;
 private String customerName;
 private String complain;

 public Customer(int customerId, String customerName, String complain) {
  super();
  this.customerId = customerId;
  this.customerName = customerName;
  this.complain = complain;
 }


 public int getCustomerId() {
  return customerId;
 }


 public void setCustomerId(int customerId) {
  this.customerId = customerId;
 }


 public String getCustomerName() {
  return customerName;
 }


 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }


 public String getComplain() {
  return complain;
 }


 public void setComplain(String complain) {
  this.complain = complain;
 }

}




2. Create a Java class which will write into XML files through Java API.

package com.hubberspot.xml.writer;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream.GetField;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;


public class XmlWriterTest {

 public static void main(String[] args) {

  createXmlDocument("C://Customer.xml");

 } 

 private static Customer[] createCustomers() {

  Customer [] customers = new Customer[3];

  Customer customer1 = new Customer(1, "John Smith", "Internet Connection problem");
  Customer customer2 = new Customer(2, "Will Foster", "DTH Service problem");
  Customer customer3 = new Customer(3, "Jonty Rhodes", "Set-Top box not working");

  customers[0] = customer1;
  customers[1] = customer2;
  customers[2] = customer3;

  return customers;
 }

 private static void createXmlDocument(String fileInfo) {

  XMLOutputFactory factory = XMLOutputFactory.newFactory();

  FileOutputStream fos;
  XMLStreamWriter writer = null;

  try {

   fos = new FileOutputStream(fileInfo);
   writer = factory.createXMLStreamWriter(fos, "UTF-8");
  } 
  catch (FileNotFoundException e) {

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

   e.printStackTrace();
  }

  writeToDocument(writer);

 }

 private static void writeToDocument(XMLStreamWriter writer) {

  try {

   writer.writeStartDocument();
   writer.writeCharacters("\n");
   writer.writeStartElement("customers");
   writer.writeCharacters("\n");
   
   for(Customer customer : createCustomers()) { 
    
    writer.writeCharacters("\t");
    writer.writeStartElement("customer");
    writer.writeAttribute("id", String.valueOf(customer.getCustomerId()));
    
    writer.writeCharacters("\n\t\t");
    writer.writeStartElement("name");
    writer.writeCharacters(customer.getCustomerName());
    writer.writeEndElement();
    
    writer.writeCharacters("\n\t\t");
    writer.writeStartElement("complain");
    writer.writeCharacters(customer.getComplain());
    writer.writeEndElement();
    
    writer.writeCharacters("\n\t");
    writer.writeEndElement();
    writer.writeCharacters("\n");
   }
   
   writer.writeEndElement();
   writer.writeEndDocument();
   writer.close();

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



Output of the program :



How to create new directory and sub-directories in Java ?.

Program to demonstrate how to create new directory and sub-directories in Java.

package com.hubberspot.io;

import java.io.File;

public class CreateNewFolder {

 public static void main(String[] args) {

  // Create a File Object and pass directory/folder name
  // as a string to it.  
  File fileStructure = new File("c:\\New Folder");

  // File object has a method called as exists() which
  // Tests whether the file or directory denoted by 
  // this abstract pathname exists. 
  if(! fileStructure.exists()) {

   // File object has a method called as mkdir() which
   // Creates the directory named by this abstract pathname. 
   if (fileStructure.mkdir()) {

    System.out.println("New Folder/Directory created .... ");

   }
   else {

    System.out.println("Oops!!! Something blown up file creation...");

   }

  } else {

   System.out.println("File already exists !!! ...");

  }

  // Create a File object and pass as a string full file structure
  // you want to create. 
  File subFiles = new File("c:\\Directory\\Sub-Folder\\Sub-Folder2");

  // File object has a method by name mkdirs() which
  // Creates the directory named by this abstract pathname,
  // it creates full file structure as it is given in as string
  // Note that if this operation fails it may have succeeded 
  // in creating some of the necessary parent directories. 

  if(subFiles.mkdirs()) {

   System.out.println("Full directory structure created ... ");

  }
  else {

   System.out.println("Oops!!! Something blown up files creation...");

  }

 }

}



Output of the program :



How to read Zip or Jar Archive File using Java ?.

Program to demonstrate how to read Zip or Jar Archive using Java.

package com.hubberspot.examples;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class ZipJarReaderDemo {

 public static void main(String[] args) {

  // 1. Working with zip files ...... 

  // Create a File and pass a .zip file to it
  File file = new File("c:\\temp.zip");

  try {

   // Create a ZipFile object by passing File object 
   // to its constructor. ZipFile Opens a ZIP file 
   // for reading File passed. 
   ZipFile zipFile = new ZipFile(file);

   // ZipFile has a method called as entries()
   // which returns an enumeration of the ZIP 
   // file entries. 
   Enumeration entries = zipFile.entries();

   // looping each file entries by using Enumeration 
   // hasMoreElements() to tests if this enumeration
   // contains more elements.
   while(entries.hasMoreElements())
   {
    // ZipEntry class represents a zip entry file in a zip
    // it is been taken by using nextElement() of Enumeration
    ZipEntry entry = (ZipEntry) entries.nextElement();

    // ZipEntry's getName() returns us the name of file in zip 
    System.out.println("Zip :> File Name : " + entry.getName());

    // Tests whether given file is a Directory or not
    if(entry.isDirectory())
    {
     System.out.println(entry.getName() + " is a Directory");
    }
    else
    {
     System.out.println(entry.getName() + " is a File ");
    }    
   }  
   // closing the zip file
   zipFile.close();
  }
  catch (ZipException e) {

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

   e.printStackTrace();
  }

  System.out.println();

  // 2. Working with jar files ...... 

  try {
   // Create a File and pass a .jar file to it
   file = new File("c:\\temp.jar");

   // Create a JarFile object by passing File object 
   // to its constructor. JarFile Opens a JAR file 
   // for reading File passed.
   JarFile jarFile = new JarFile(file);

   // JarFile has a method called as entries()
   // which returns an enumeration of the JAR 
   // file entries.
   Enumeration entries = jarFile.entries();

   // looping each file entries by using Enumeration 
   // hasMoreElements() to tests if this enumeration
   // contains more elements.
   while(entries.hasMoreElements())
   {
    // JarEntry class represents a jar entry file in a jar
    // it is been taken by using nextElement() of Enumeration
    JarEntry entry = (JarEntry) entries.nextElement();

    // JarEntry's getName() returns us the name of file in jar
    System.out.println("Jar :> File Name : " + entry.getName());

    // Tests whether given file is a Directory or not
    if(entry.isDirectory())
    {
     System.out.println(entry.getName() + " is a Directory");
    }
    else
    {
     System.out.println(entry.getName() + " is a File ");
    }    
   } 

   // closing the jar file
   jarFile.close();
  }
  catch(IOException io)
  {
   io.printStackTrace();
  }
 }
}



Output of the program :





Video tutorial to demonstrate how to create a Zip File in Java







How to Copy a file from one location to another in Java ?.


Program to demonstrate how to Copy a file from one location to another in Java.

package com.hubberspot.code;

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


public class CopyFile {

 public static void main(String[] args) {

  // Create a Scanner object which takes System.in object
  // this makes us read values from the console

  Scanner scanner = new Scanner(System.in);

  // In order to copy a file from one location 
  // to another 
  // We will prompt user to enter path of file 
  // in current location and path 
  // of the location where it wants to copy the file

  // Prompting user to enter path of current location 
  // of file
  System.out.println("Enter the path of current location of file : ");

  // Scanner objects nextLine() reads output from the console
  // entered by user and stores into the string variable
  String currentPath = scanner.nextLine().trim();  

  // Prompting user to enter path of target location of file  
  System.out.println("Enter the path of target location of file : ");

  String targetLocation = scanner.nextLine().trim();

  System.out.println();

  // Creating a new file object by passing current file name and
  // target file name along with the location
  File currentFile  = new File(currentPath);
  File targetFile  = new File(targetLocation);  

  // Creating FileOutputStream and FileInputStream variables 
  FileOutputStream fileOutputStream = null;

  FileInputStream fileInputStream = null;
  try {

   // Wrapping the File objects created above within 
   // FileOutputStream and FileInputStream objects
   fileOutputStream = new FileOutputStream(currentFile);
   fileInputStream = new FileInputStream(targetFile);

   // Creating a buffer of byte for storing contents of file
   byte[] buffer = new byte[4096];
   int read;

   // looping the file contents on the current location till
   // it becomes empty
   while ((read = fileInputStream.read(buffer)) != -1) {

    // As each loops terminates the target file gets the 
    // contents of current file in the chunks of buffer 
    fileOutputStream.write(buffer, 0, read);
   }

   // catch blocks for closing of the streams and catching 
   // IOException
  } catch(IOException e) {

   try {
    e.printStackTrace();
    if (fileInputStream != null) {

     fileInputStream.close();     

    }
    if (fileOutputStream != null) {

     fileOutputStream.flush(); 
     fileOutputStream.close();

    }
   }
   catch (IOException e1) {

    e1.printStackTrace();
   }
  }

 }

}





Output of the program : 


 

How to get and print last modification date of a file on the console in Java ?.

Program to demonstrate how to get and print last modification date of a file on the console in Java.

package com.hubberspot.code;

import java.io.File;
import java.util.Date;


public class ModifiedDate {

 public static void main(String[] args) {

  // Creating a new File Object by passing filename to it
  File file = new File("customer.txt");

  // Getting the last modified date by calling 
  // lastModified() method of the file object
  long modified = file.lastModified();

  // Creating a new date object by passing the modified long
  // value to its constructor
  Date lastModifiedDate = new Date(modified);

  // printing the initial modified date to the console
  System.out.println("Initial Modification Date : \n");
  System.out.println(lastModifiedDate);

  System.out.println("\nMaking the main thread sleep for 10 sec ... ");
  System.out.println("Till than modifying the file to print new modified date... ");

  try {
   Thread.sleep(10000);
  }
  catch (InterruptedException e) {

   e.printStackTrace();
  }

  // till main thread is at sleep for 10 sec 
  // we are modifying the file contents and saving
  // the file to print the new modified date 
  modified = file.lastModified();

  lastModifiedDate = new Date(modified);

  System.out.println("\nAfter Modification Date : \n");
  System.out.println(lastModifiedDate);

 }

}



Output of the program : 


 

A simple Java program to read and download a Web page in a html file

Program to demonstrate how to read and download a webpage in a html file, in Java

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlDownload {

   public static void main(String[] args) {

      try {
 // Create a URL object and pass url as string
 // to download the webpage 
 // 
 URL url = new URL("http://www.hubberspot.com");
 // Create a BufferedReader Object and pass it with
 // InputStreamReader Object containing an InputStream
 // Object retrieved  from openStream() method of URL
 BufferedReader reader = new BufferedReader
                      (new InputStreamReader(url.openStream()));
 // Create a BufferedWriter Object and pass it with
 // FileWriter Object containing an String
 // representing the file name to which 
 // the webpage is to download. 
 BufferedWriter writer = new BufferedWriter
                      (new FileWriter("hubberspot.html"));
 // Create a String object to read each line 
 // one by one from the stream
 String line;
 // looping till there is no line left to download
 while ((line = reader.readLine()) != null) {
 // Writing each line in the document hubberspot.html 
     writer.write(line);
     // to print each line on next line 
     writer.newLine();
 }
 // Closing the BufferedReader and BufferedWriter object 
 // to free the expensive resources
 reader.close();
 writer.close();
 }// handling two exceptions below 
 // In case URL is malformed MalformedURLException
 // Exception is thrown and 
 // IOException for any input/output failure
    catch (MalformedURLException e) {
 
 e.printStackTrace();
   } catch (IOException e) {
 
 e.printStackTrace();
  }
 }

}




Output of the program :



A simple program demonstrating how to store properties to an XML file ?

A simple program demonstrating how to store properties to an XML file

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;


public class StoreXmlDemo {
 
   public static void main(String[] args) {
  
 String file = "customer.xml";
  
 // Create a FileOutputStream by providing
 // name of file 
 FileOutputStream fis;
 try {
           fis = new FileOutputStream(file);
  
    // Create a Properties Object
    Properties properties = new Properties();
    // Set few properties on it 
           properties.setProperty("firstname", "Jonty");
           properties.setProperty("lastname", "Magicman");
           properties.setProperty("email", "Jonty@magic.com");
           // After setting properties, try to store in the xml
           // by calling storeToXML() method
    properties.storeToXML(fis, "CustomerInfo", "UTF-16");
 
 } catch (FileNotFoundException e) {
   
  e.printStackTrace();
 } catch (IOException e) {
   
  e.printStackTrace();
 }
   }

}




Output of the program :




A simple program demonstrating how to load properties from an xml file ?

A simple program demonstrating how to load properties from an xml file

import java.io.FileInputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;


public class LoadXmlDemo {
 
   public static void main(String[] args) {
  
 LoadXmlDemo load = new LoadXmlDemo();
 
 Properties properties = load.getProperties();
 String email = properties.getProperty("email");
 String firstname = properties.getProperty("firstname");
 String lastname = properties.getProperty("lastname");
  
 System.out.println("Email of the Customer : " + email);
 System.out.println("Firstname of the Customer : " + firstname);
 System.out.println("Lastname of the Customer : " + lastname);

   }
 
   public Properties getProperties() {
 Properties prop = new Properties();
 try {
            FileInputStream fis = new FileInputStream("Customer.xml");
      
     prop.loadFromXML(fis);
   
 } catch (InvalidPropertiesFormatException e) {
   
    e.printStackTrace();
 } catch (IOException e) {
   
    e.printStackTrace();
 }
 return prop;
   }
}



XML file used to load properties :













Output of the program : 






How to Capture Screen through a Java program using Robot class ?.

Program to demonstrate screen capture through a Java program using Robot class.

package com.hubberspot.example;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class RobotScreenCapture {
 
   public static void main(String[] args) {
  
 try {
   
 // 1. Create a Robot Object 
 Robot robot = new Robot();
        // 2. Create a Dimension Object for the screen capture 
 // by providing width and height for the screen area 
 Dimension dimension = new Dimension(300,300);
 // 3. Create a Rectangle by taking the dimension reference
 // to create a screen capture of area specified by dimension 
 Rectangle screen = new Rectangle(dimension);
 // 4. Calling createScreenCapture method of Robot class by 
 // passing it Rectangle reference. It will return a reference 
 // to a BufferedImage Object.  
 BufferedImage buffer = robot.createScreenCapture(screen);
 // 5. Create a file to store the image 
 File screenCapture = new File("screen.jpg");
 // 6. Call the write method of ImageIO class by passing
 // it BufferedImage and File created above 
 ImageIO.write(buffer, "jpg", screenCapture);
   
 } catch (AWTException e) {   
  e.printStackTrace();
 } catch (IOException e) {  
  e.printStackTrace();
 } 

   }

}




Output of the program :



How to Play an MP3 File in Java ?

In order to play Mp3 files in Java , you need to download  jl1.0.jar from the website  javazoom.net. After downloading put the jar into Eclipse or Netbeans buildpath and execute below code.


Program to demonstrate how to play Mp3 files in Java

package com.hubberspot.example;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;


public class Mp3Player {
   
    private String filename;
    private Player player; 


    public Mp3Player(String filename) {
 this.filename = filename;
    }


    public void play() {
 try {   
            BufferedInputStream buffer = new BufferedInputStream(
    new FileInputStream(filename));
     player = new Player(buffer);
     player.play();
 }
 catch (Exception e) {

     System.out.println(e);
 }

    }

    public static void main(String[] args) {
 Mp3Player mp3 = new Mp3Player("song.mp3");
 mp3.play();

    }

}




A simple Java program demonstrating how to read and write Images to a file ?

Program to demonstrate how to read and write Image to a file in Java

package com.hubberspot.example;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

public class ReadWriteImageDemo {

   public static void main(String[] args) {
 ReadWriteImageDemo demo = new ReadWriteImageDemo();
 demo.imageProcessing();
   }

   public void imageProcessing(){
 try {

 // url of the image is wrapped in URL Object
 URL url = new URL("http://1.bp.blogspot.com/-YUR1RgiOqW0/" +
 "UC1UBYT7zZI/AAAAAAAAAeo/g34uyKSvTBI/s1600/Robot+keypress+event.jpg");
   
        // BufferedImage ref variable holds the image read at specified URL 
 // by the ImageIO class through its static method read() 
   
 BufferedImage imageUrl = ImageIO.read(url);
   
 // BufferedImage ref variable holds the image read at specified File
 // by the ImageIO class through its static method read()
   
 BufferedImage image = ImageIO.read(new File("out.gif"));
           
 // ImageIO's class static method takes RenderedImage ,
        // formatName, File and creates or transfer rendered image to 
 // File Object 
 
 ImageIO.write(imageUrl, "gif",new File("outUrl.gif"));
 ImageIO.write(image, "gif",new File("url.jpg"));


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


    }
}




Output of the program :

After reading Images from url and file system, ImageIO write method will create two image files with the name as : outUrl.jpg and url.jpg. There must be internet connection so that image at Url can be fetched successfully.

How to convert InputStream data to String data in Java ?.


Program to how to convert InputStream data to String data in Java.


package com.hubberspot.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class InputStreamToString {

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

 InputStreamToString ists = new InputStreamToString();

 InputStream inputStream =
   ists.getClass().getResourceAsStream("/customer.txt");

 if (inputStream != null) {

  char[] charBuffer = new char[1024];
  Writer outputToConsole = new StringWriter();
  try {
   Reader readFromFile = new BufferedReader(
     new InputStreamReader(inputStream));
   int i;
   while ((i = readFromFile.read(charBuffer)) != -1) {
    outputToConsole.write(charBuffer, 0, i);
   }
  } finally{
   System.out.println(outputToConsole.toString());
   inputStream.close();
  }
 }     
   } 
}



customer.txt














Output of the program : 


 

How to pass input from a console to a Java program ?.


In this section of blog, we will look into a tutorial and a simple Java program, explaining how to pass input from a console to a Java program. Usually, Input is given to the program from the standard input device called as keyboard. In Java reading an input is not as simple as output. Java API is full of several classes which can be used for the purpose of reading the input from a keyboard.

System.in is a predefined stream object which can be used to read input. But System.in is a byte oriented stream, it can be used only to read bytes. In order to make it read characters we usually wrap it across a character oriented stream called as InputStreamReader. InputStreamReader is a reader class which is been used to read characters. For reading the input as string we wrap this byte stream to BufferedReader which buffers characters.

In order to apply above concepts to these streams we follow these steps :


1. BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

2. InputStreamReader isr = new InputStreamReader(
System.in);
BufferedReader br = new BufferedReader(isr);


In order to read a string, we use method readLine on the BufferedReader object as

String read = br.readLine();

Program to demonstrate how to pass input from console to a Java program in order to calculate sum and average of numbers as wished by user

package com.hubberspot.streams.example;

import java.io.*;
public class ConsoleReader {

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

int number, sum=0, n, i;
float avg;

BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("How many numbers? ");

n = Integer.parseInt(br.readLine());

 for(i=0; i < n ; i++)
{
System.out.println("Enter number " + (i+1));

number = Integer.parseInt(br.readLine());
sum += number;
}

avg = sum / n;

System.out.println("Sum of numbers is = " + sum);
System.out.println("Average of numbers is = "+ avg);

}
} 


Output of the program :





Program to demonstrate how to display File information in Java ?.

Introduction
In this section of blog, we will look into a simple program that will demonstrate how to display File information in Java. The methods used here are defined in File class present in java.io.* package. For more details of this method read my blog post : Creating objects and methods list of File class in Java

package com.hubberspot.file.example;

import java.io.*;

/**
 *
 * @author Jontymagicman
 */

public class FileInformation {
  public static void main(String[] args){
        
    File file = new File("E:\\notepad.txt");
        
    System.out.println("File Name : "+ file.getName()); 
 
 System.out.println("File last modified : "+ file.lastModified()); 
 
 System.out.println("File size : " + file.length() + " Bytes"); 
 
 System.out.println("Path : "+file.getPath()); 
 
 System.out.println("Abs Path : "+file.getAbsolutePath()); 
 
 System.out.println("Parent : "+ file.getParent()); 
 
    System.out.println(file.exists() ? +
+"File exists":"File does not exist"); 
 
    System.out.println(file.canWrite() ? +
+"File is writable" : "File is not writable"); 
 
 System.out.println(file.canRead() ? +
+"File is readable" : "File is not readable"); 
 
    System.out.println(file.isHidden() ? +
+"File is hidden" : "File is not hidden"); 
 
 System.out.println(file.isDirectory() ? +
+"Is a directory" : "Is not a directory"); 
 
    System.out.println(file.isFile() ? +
+"Is a file" : "Is not a file"); 
 
    System.out.println(file.isAbsolute() ? +
+"File is absolute" : "File is not absolute" );
        
  }
    
}

Output of the program




Creating objects and methods list of File class in Java

Introduction :-

Hello friends, In this hub, I will be creating and demonstrating the working of File objects in Java. Before we go further, lets go in the basics of importance of files in computers. Generally, data stored in variables and objects are not permanent. They are not persistent. They are normally temporary data which remains in memory as long as the scope of variable. Once a local variable gets out of scope the data is lost. So to keep the data for long time use generally computer uses files. These files are been stored in secondary storage devices such as hard disk, flash drives etc. The data stored in them is permanent.In terms of programming language such as Java, terms like Files and Streams have their own meaning. Java actually sees a file as a stream of bytes which is sequential.
Java provides us a package called as java.io package. This package consist of class File which helps in retrieving information about various files and various directories in disk. Generally they don't provide capabilities such as opening or closing a file and basic processing of a file or directory. However File objects are frequently used with other objects in java.io package to do the above processing of the files and directories.

Creating File Objects :-

File Objects are created with new operator, which calls constructor with four different arguments. One of the constructor requires string passed to it as argument. This string provides the constructor name of the file or directory. The name usually is the path given to constructor where File object can locate the file or directory. The path information provided into the constructor can be either relative or absolute path. The relative path deals with current directory from where the application has began. The absolute path starts from a root directory and proceed to name of the file or directory specified. Another constructor has two arguments passed to it, first argument contains the relative or the absolute path to file directory and the second argument contains the name of the file or directory , which we want to associate to File object. Another constructor with File and String argument is used. Here we use existing File object which points to file or directory specified by the String argument. The last constructor uses the URI as an argument to point to the file or directory. Here by URI we mean Uniform Resource Identifier which are like Uniform Resource Locators. They use URL like pattern to locate the files, e.g. file://C:/java-programs.txt.

Constructors of File :-
File (String path);
File (String path, String name);
File (File obj, String name);
File (URI);

Important methods of File class
  1. boolean isFile() :- This method return either true or false. It return true if the File object created by passing a String object to it, is an existing file.
  2. boolean isDirectory() :- This method return either true or false. It return true if the File object created by passing a String object to it, is an existing directory.
  3. boolean exists() :- This method returns true if the file / directory represented by the object exists.
  4. boolean canWrite() :- It returns true if the current application can write the file.
  5. boolean canRead() :- It returns true if the current application can read the file.
  6. boolean isAbsolute() :- It returns true if the path specified as String in the File object constructor is absolute.
  7. String[ ] list() :- If you want directory's content in the form of array of string this method is used. It returns null if the file specified in the argument is not directory.
  8. long lastModified() :-It provides us with the time, that when a file was last modified.
  9. long length() :- It returns the length of the file in bytes. If its a directory, an unusual value is returned.
  10. String getPath() :- It basically returns the path of the file in use.
  11. String getParent() :- It basically returns the name of parent directory holding the file .
  12. String getName() :- It return name of the file used at the time of creating File object
  13. String getAbsolutePath() :- It basically returns the absolute path of file or directory.
  14. String getCanonicalPath() :- Returns the path of the file object but separators in the path name are system-dependent separators such as / or \.
  15. Boolean isHidden() :- Returns true if the file is hidden and false otherwise.
  16. Boolean renameTo(File name) :- Renames the file (or directory) represented by this File instance to the new name specified by Name.
  17. boolean delete() :- Deletes the file or directory associated with the File object.
  18. boolean createNewFile() :- Creates a new file with the specified name if it does not exists.
  19. boolean mkdir() :- Creates a directory by using the abstract path name associated with this File instance.
  20. boolean mkdirs() :- Creates a directory by using the abstract path name associated with this File instance. Also creates any non-existent parent directories appearing in the given path.
  21. File [ ] listFiles() :- Returns an array that contains the names of files only contained in the directory represented by this File instance. 


     
    © 2021 Learn Java by Examples Template by Hubberspot