Thursday, December 12, 2019

How To Practice File In Addition To Directory Inwards Coffee Amongst Example

Many beginners confused amongst the fact that same class java.io.File is used to create both file together with directory inwards Java. I agree, this is non really intuitive together with  junior developers in all likelihood get-go looking for a shape called java.io.Directory, which doesn't exists. On the other hand, creating file together with directory are unproblematic inwards Java, as java.io.File provides methods like createNewFile() and mkdir() to do novel file together with directory inwards Java. These method returns boolean, which is the upshot of that performance i.e. createNewFile() returns truthful if it successfully created file together with mkdir() returns truthful if the directory is created successfully. There is roughly other method called mkdirs(), which you lot tin purpose if nurture directory doesn't exist, it's like mkdir -p option from UNIX mkdir command. In this Java program, nosotros volition acquire how to do file together with directory, entirely if they don't be already.

For checking, whether a file or directory exists or not, nosotros volition use java.io.File.exists() method, this method returns true, if file or directory is already there. To come across consummate demeanor inwards action, delight run this plan twice amongst same inputs. First fourth dimension it volition do directory together with file, together with mo time, it volition merely say that they already exists.



Java Program to brand File together with Directory

This is the consummate code of our sample Java plan to do file together with directory inwards Java. As I told same object java.io.File is used to correspond both file together with directory,  its of import to cite variable properly to distinguish betwixt them e.g. using prefix "f" for file together with "dir" for directory, or something similar.  In this example, nosotros are hollo for user to acquire into path of directory to live created, and using scanner to read information from console. Scanner.nextLine() returns a String, thence no demand of whatever additional parsing.


After that nosotros are checking if directory already exists or non past times using exists() method from java.io.File class, extremely useful to forbid accidental overwrite of one-time data. If directory doesn't already exists thence nosotros call mkdir() method from File class to genuinely do a directory, thankfully cite is similar to pop ascendency mkdir, which is used to do directory inwards both Windows together with Linux operating systems. This method returns a boolean value, which tin live used to banking corporation tally if creation of directory is successful or not, you lot tin either leverage this value for fault treatment or printing fault message.

Once directory is ready, nosotros are creating a File object past times passing string path. This file object is farther used to banking corporation tally if whatever file of same cite already exists on same place or not. If non thence entirely nosotros do file, using createNewFile() of java.io.File class. 

 Many beginners confused amongst the fact that same shape How to Create File together with Directory inwards Java amongst Example
Similar to mkdir() method, this equally good returns a boolean to piece of occupation past times upshot of operation. It volition render truthful if file is successfully created otherwise false, which may live due to diverse reasons e.g. non having sufficient permissions to do file, or at that topographic point is non plenty infinite to accommodate new files etc. After creating, you lot tin also purpose Scanner to read file inwards Java, equally shown inwards that article.

Code Sample

import java.io.File; import java.io.IOException; import java.util.Scanner;  /** * Simple Java plan to do File together with Directory inwards Java, without using * whatever third-party library.
* @author http://java67.blogspot.com * */ public class FileDemo {      public static void main(String args[]) throws IOException {          Scanner reader = new Scanner(System.in);         boolean success = false;          System.out.println("Enter path of directory to create");         String dir = reader.nextLine();          // Creating novel directory inwards Java, if it doesn't exists         File directory = new File(dir);         if (directory.exists()) {             System.out.println("Directory already exists ...");          } else {             System.out.println("Directory non exists, creating now");              success = directory.mkdir();             if (success) {                 System.out.printf("Successfully created novel directory : %s%n", dir);             } else {                 System.out.printf("Failed to do novel directory: %s%n", dir);             }         }          // Creating novel file inwards Java, entirely if non exists         System.out.println("Enter file cite to live created ");         String filename = reader.nextLine();          File f = new File(filename);         if (f.exists()) {             System.out.println("File already exists");          } else {             System.out.println("No such file exists, creating now");             success = f.createNewFile();             if (success) {                 System.out.printf("Successfully created novel file: %s%n", f);             } else {                 System.out.printf("Failed to do novel file: %s%n", f);             }         }          // closed Scanner to forbid resources leak         reader.close();      } }  Output :  First run : Enter path of directory to do C:\dhoom3 Directory non exists, creating straightaway Successfully created new directory : C:\dhoom3 Enter file cite to live created Abhishek.txt No such file exists, creating straightaway Successfully created new file: Abhishek.txt  Second run : Enter path of directory to do C:\dhoom3 Directory already exists ... Enter file cite to live created Abhishek.txt File already exists

Don't forget to closed Scanner ane time done, a expert do to forbid resources leak inwards Java. Alternatively you lot tin equally good purpose try-with-resource statements from Java 7, which facilitate automatic resources construct clean up for you. That non entirely accept assist of releasing resources ane time you lot are done amongst that, but equally good removes coding headache together with endure block from inwards a higher house code, making it to a greater extent than concise together with readable. That's all nigh how to do or brand file together with directory inwards Java.
Further Learning
Data Structures together with Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass


No comments:

Post a Comment