Difference between revisions of "JAVA: Create File Baru"

From OnnoWiki
Jump to navigation Jump to search
(Created page with " A File is an abstract path, it has no physical existence. It is only when “using” that File that the underlying physical storage is hit. When the file is getting created...")
 
Line 2: Line 2:
 
A File is an abstract path, it has no physical existence. It is only when “using” that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement.
 
A File is an abstract path, it has no physical existence. It is only when “using” that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement.
  
Steps to Create a New File in Java
+
==Steps to Create a New File in Java==
 
1. Primary, in order to create a new file, inbuilt files and functions are used which definitely will throw Exceptions here playing it safe. So in order to deal with it, we will be using Exception Handling Techniques. Here, we will use one of them known as-try-catch block techniques.  
 
1. Primary, in order to create a new file, inbuilt files and functions are used which definitely will throw Exceptions here playing it safe. So in order to deal with it, we will be using Exception Handling Techniques. Here, we will use one of them known as-try-catch block techniques.  
  
Line 9: Line 9:
 
Syntax: To import file library or Classes
 
Syntax: To import file library or Classes
  
import java.util.File ;
+
import java.util.File ;
 +
 
 
Syntax: To create a new file
 
Syntax: To create a new file
  
File object_name = new File(Directory)
+
File object_name = new File(Directory)
 +
 
 
Syntax: To specify a directory is different in different operating systems (suppose java file is in a folder named ‘Folder’ is created on desktop)
 
Syntax: To specify a directory is different in different operating systems (suppose java file is in a folder named ‘Folder’ is created on desktop)
  
 
In Linux and Mac
 
In Linux and Mac
  
/Users/mayanksolanki/Desttop/Folder/
+
/Users/mayanksolanki/Desttop/Folder/
 +
 
 
In Windows: ‘ \\ ‘ used instead of  ‘ / ‘ to escape ‘ \ ‘ character. So the same directory is accessed as
 
In Windows: ‘ \\ ‘ used instead of  ‘ / ‘ to escape ‘ \ ‘ character. So the same directory is accessed as
  
\\Users\\mayanksolanki\\Desktop\\Folder\\
+
\\Users\\mayanksolanki\\Desktop\\Folder\\
 +
 
 
There are two standards methods to create a new file either directly with the help of File class or indirectly with the help of FileOutputStream by creating an object of the file in both the approaches.
 
There are two standards methods to create a new file either directly with the help of File class or indirectly with the help of FileOutputStream by creating an object of the file in both the approaches.
  
Line 46: Line 50:
 
Directory Used : /Users/mayanksolanki/Desktop/Folder/  
 
Directory Used : /Users/mayanksolanki/Desktop/Folder/  
  
Method 1: Create a new file using the File class  
+
==Method 1: Create a new file using the File class==
 +
 
 +
// Java Program to create new file using File class
 +
 
 +
// Importing new files
 +
import java.io.File;
 +
import java.io.BufferedReader;
 +
 
 +
// Importing as it converts bits to strings
 +
import java.io.InputStreamReader;
 +
 
 +
public class GFG {
 +
 
 +
    // Main Driver Method
 +
    public static void main(String args[])
 +
    {
 +
        // Creating New File via function
 +
        GFG gfg = new GFG();
 +
        gfg.newFile();
 +
    }
 +
 
 +
    // Function To Make New File
 +
    public void newFile()
 +
    {
 +
        String strPath = "", strName = "";
 +
 
 +
        // Try-catch Block
 +
        try {
 +
 
 +
            // Creating BufferedReadered object
 +
            BufferedReader br = new BufferedReader(
 +
                new InputStreamReader(System.in));
 +
            System.out.println("Enter the file name:");
 +
 
 +
            // Reading File name
 +
            strName = br.readLine();
 +
            System.out.println("Enter the file path:");
 +
 
 +
            // Reading File Path
 +
            strPath = br.readLine();
 +
 
 +
            // Creating File Object
 +
            File file1
 +
                = new File(strPath + "" + strName + ".txt");
 +
 
 +
            // Method createNewFile() method creates blank
 +
            // file.
 +
            file1.createNewFile();
 +
        }
 +
 
 +
        // Try-Catch Block
 +
        catch (Exception ex1) {
 +
        }
 +
    }
 +
}
  
// Java Program to create new file using File class
 
 
 
// Importing new files
 
import java.io.File;
 
import java.io.BufferedReader;
 
 
 
// Importing as it converts bits to strings
 
import java.io.InputStreamReader;
 
 
 
public class GFG {
 
 
 
    // Main Driver Method
 
    public static void main(String args[])
 
    {
 
        // Creating New File via function
 
        GFG gfg = new GFG();
 
        gfg.newFile();
 
    }
 
 
 
    // Function To Make New File
 
    public void newFile()
 
    {
 
        String strPath = "", strName = "";
 
 
 
        // Try-catch Block
 
        try {
 
 
 
            // Creating BufferedReadered object
 
            BufferedReader br = new BufferedReader(
 
                new InputStreamReader(System.in));
 
            System.out.println("Enter the file name:");
 
 
 
            // Reading File name
 
            strName = br.readLine();
 
            System.out.println("Enter the file path:");
 
 
 
            // Reading File Path
 
            strPath = br.readLine();
 
 
 
            // Creating File Object
 
            File file1
 
                = new File(strPath + "" + strName + ".txt");
 
 
 
            // Method createNewFile() method creates blank
 
            // file.
 
            file1.createNewFile();
 
        }
 
 
 
        // Try-Catch Block
 
        catch (Exception ex1) {
 
        }
 
    }
 
}
 
 
Output:   
 
Output:   
  
Line 111: Line 116:
 
Added file name            : newFile.txt
 
Added file name            : newFile.txt
 
Added file name directory : /Users/mayanksolanki/Desktop/Folder/
 
Added file name directory : /Users/mayanksolanki/Desktop/Folder/
 +
 
Explanation:
 
Explanation:
  
Line 124: Line 130:
 
Here “createNewFile()” method is called with the help of the File class object. This method creates a blank file on a given directory path.
 
Here “createNewFile()” method is called with the help of the File class object. This method creates a blank file on a given directory path.
 
Lastly, enclosed by “try{ }” block. Because, methods like readLine() and createNewFile() methods generates exception. So to handle that exception try, the catch is used.
 
Lastly, enclosed by “try{ }” block. Because, methods like readLine() and createNewFile() methods generates exception. So to handle that exception try, the catch is used.
Method 2: Create a new file using FileOutputStream class
 
  
// Java Program to create new file
+
==Method 2: Create a new file using FileOutputStream class==
// using FileOutputStream class
+
 
 
+
// Java Program to create new file
// Importing File Classes
+
// using FileOutputStream class
import java.io.FileOutputStream;
+
 
 
+
// Importing File Classes
// Importing BufferedReader Class for taking input
+
import java.io.FileOutputStream;
import java.io.BufferedReader;
+
 
 
+
// Importing BufferedReader Class for taking input
// Importing as it converts bits to strings
+
import java.io.BufferedReader;
import java.io.InputStreamReader;
+
 
 
+
// Importing as it converts bits to strings
// Function Helping Create New File
+
import java.io.InputStreamReader;
public class GFG {
+
 
 
+
// Function Helping Create New File
    // Main Driver Method
+
public class GFG {
    public static void main(String args[])
+
 
    {
+
    // Main Driver Method
        // Creating File Object
+
    public static void main(String args[])
        GFG gfg = new GFG();
+
    {
        gfg.newFile();
+
        // Creating File Object
    }
+
        GFG gfg = new GFG();
 
+
        gfg.newFile();
    // Function To Create A New File
+
    }
    public void newFile()
+
 
    {
+
    // Function To Create A New File
        String strFilePath = "", strFileName = "";
+
    public void newFile()
 
+
    {
        // Try-Catch Block
+
        String strFilePath = "", strFileName = "";
        try {
+
 
 
+
        // Try-Catch Block
            // Creating BufferClass Object
+
        try {
            BufferedReader br = new BufferedReader(
+
 
                new InputStreamReader(System.in));
+
            // Creating BufferClass Object
            System.out.println("Enter the file name:");
+
            BufferedReader br = new BufferedReader(
 
+
                new InputStreamReader(System.in));
            // Asking file name from User
+
            System.out.println("Enter the file name:");
            strFileName = br.readLine();
+
 
            System.out.println("Enter the file path:");
+
            // Asking file name from User
 
+
            strFileName = br.readLine();
            // Asking file path from User
+
            System.out.println("Enter the file path:");
            strFilePath = br.readLine();
+
 
 
+
            // Asking file path from User
            // Creating Object of FileOutputStream Class
+
            strFilePath = br.readLine();
            FileOutputStream fos = new FileOutputStream(
+
 
                strFilePath + "" + strFileName + ".txt");
+
            // Creating Object of FileOutputStream Class
        }
+
            FileOutputStream fos = new FileOutputStream(
 
+
                strFilePath + "" + strFileName + ".txt");
        // Try-Catch Block
+
        }
        catch (Exception ex1) {
+
 
        }
+
        // Try-Catch Block
    }
+
        catch (Exception ex1) {
}
+
        }
 +
    }
 +
}
 
   
 
   
 
Explanation:
 
Explanation:

Revision as of 13:38, 7 May 2022

A File is an abstract path, it has no physical existence. It is only when “using” that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement.

Steps to Create a New File in Java

1. Primary, in order to create a new file, inbuilt files and functions are used which definitely will throw Exceptions here playing it safe. So in order to deal with it, we will be using Exception Handling Techniques. Here, we will use one of them known as-try-catch block techniques.

2. Secondary, additional work is simply we will be importing File Class for which we will be importing File Class.

Syntax: To import file library or Classes

import java.util.File ;

Syntax: To create a new file

File object_name = new File(Directory)

Syntax: To specify a directory is different in different operating systems (suppose java file is in a folder named ‘Folder’ is created on desktop)

In Linux and Mac

/Users/mayanksolanki/Desttop/Folder/

In Windows: ‘ \\ ‘ used instead of ‘ / ‘ to escape ‘ \ ‘ character. So the same directory is accessed as

\\Users\\mayanksolanki\\Desktop\\Folder\\

There are two standards methods to create a new file either directly with the help of File class or indirectly with the help of FileOutputStream by creating an object of the file in both the approaches.

By using File Class By using FileOutputStream Class File Class

FileOutputStreamClass

It is a class that is just a handle for It is an output stream that can be written to FileOutputStream JavaDoc Method: File.createNewFile() Method: FileOutputStream

Example: echo > myFile.txt

It is used for those objects which do not have physical existence It is used for those objects which are already existing Both classes provide some methods which are mainly used to do operations regarding files. For example, to create, to write, to compare two path names, to check whether a specific file is present or not, and many more. To understand this topic, first, consider one example for both approaches.

Terminal Command used to compile any java code on the machine Terminal Command used to Run any java code on the machine javac class_name.java // For Compilation java class_name // For Execution Terminal of Mac operating system will be used for implementation and providing an output of accessing the directory

Directory Used : /Users/mayanksolanki/Desktop/Folder/

Method 1: Create a new file using the File class

// Java Program to create new file using File class
  
// Importing new files
import java.io.File;
import java.io.BufferedReader;
  
// Importing as it converts bits to strings
import java.io.InputStreamReader;
  
public class GFG {
  
    // Main Driver Method
    public static void main(String args[])
    {
        // Creating New File via function
        GFG gfg = new GFG();
        gfg.newFile();
    }
  
    // Function To Make New File
    public void newFile()
    {
        String strPath = "", strName = "";
  
        // Try-catch Block
        try {
  
            // Creating BufferedReadered object
            BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
            System.out.println("Enter the file name:");
  
            // Reading File name
            strName = br.readLine();
            System.out.println("Enter the file path:");
  
            // Reading File Path
            strPath = br.readLine();
  
            // Creating File Object
            File file1
                = new File(strPath + "" + strName + ".txt");
  
            // Method createNewFile() method creates blank
            // file.
            file1.createNewFile();
        }
  
        // Try-Catch Block
        catch (Exception ex1) {
        }
    }
}

Output:


Name of file to be added : newFile.txt Directory where file is to be addeed : /Users/mayanksolanki/Desktop/Folder/


Added file name : newFile.txt Added file name directory : /Users/mayanksolanki/Desktop/Folder/

Explanation:

To create a new file using java language, the “File” class is used here. “BufferedReader” and “InputStreamReader” both classes are used to make file names and paths from the user as input. These classes are located inside the “java.io” package. So to make use of those classes, it is necessary to import those classes at the beginning of the program. Here class is created namely, “GFG”. And inside that class “main()” method is defined from which execution will be started. Inside the “main()” method object of the class is created. And this object is used to call the “newFile()” method. Outside of the main() method, the newFile() method is declared which is covers code for taking input from the user and create the file as per input. As the file have its own name and path, it is necessary to give a name for the file (which we want to create) and a path (where to create the file) for the file. In this line, two blank strings are declared namely, strName, strPath. “strName, and strPath are used to store the name and path of the file when the user gives this information. To take file name and path from the user as input, here BufferedReader class and InputStreamReader class are used. The object of BufferedReader “br” is useful to take input values given by the user. This line print some text to give an indication to the user like ”Enter the file name:”. To print the text “println()” function is used. Here “readLine()” method is used to take input and store it, in strName and strPath. Here object of the File class is created and as a parameter, the file path and name are given to the constructor. In this line of code “.txt” is a format of the file. You can change it as per need. The object of the File class is necessary to call methods provided in its class. Here “createNewFile()” method is called with the help of the File class object. This method creates a blank file on a given directory path. Lastly, enclosed by “try{ }” block. Because, methods like readLine() and createNewFile() methods generates exception. So to handle that exception try, the catch is used.

Method 2: Create a new file using FileOutputStream class

// Java Program to create new file
// using FileOutputStream class
  
// Importing File Classes
import java.io.FileOutputStream;
  
// Importing BufferedReader Class for taking input
import java.io.BufferedReader;
  
// Importing as it converts bits to strings
import java.io.InputStreamReader;
  
// Function Helping Create New File
public class GFG {
  
    // Main Driver Method
    public static void main(String args[])
    {
        // Creating File Object
        GFG gfg = new GFG();
        gfg.newFile();
    }
  
    // Function To Create A New File
    public void newFile()
    {
        String strFilePath = "", strFileName = "";
  
        // Try-Catch Block
        try {
  
            // Creating BufferClass Object
            BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
            System.out.println("Enter the file name:");
  
            // Asking file name from User
            strFileName = br.readLine();
            System.out.println("Enter the file path:");
  
            // Asking file path from User
            strFilePath = br.readLine();
  
            // Creating Object of FileOutputStream Class
            FileOutputStream fos = new FileOutputStream(
                strFilePath + "" + strFileName + ".txt");
        }
  
        // Try-Catch Block
        catch (Exception ex1) {
        }
    }
}

Explanation:

In the second example, the File class is not used to create a new File programmatically.

To create a new file using java language, “FileOutputStream” class is used here and “BufferedReader” & “InputStreamReader” both are used to take file name and path from the user as input. These classes are located inside of “java.io” package. So to make use of those classes, it is necessary to import them at the beginning of the program. Class is created namely, “GFG”. And inside that class “main()” method is defined from which execution will be started. Inside of “main()” method object of the class is created. And this object is used to call the “newFile()” method. Outside of the main() method, the newFile() method is declared which is covers code for taking input from the user and create a file as per input. In this line, two blank strings are declared namely, strFileName, strFilePath. “strFileName and strFilePath are used to store the name and path of the file when the user gives this information. To take file name and path from the user as input, here BufferedReader class and InputStreamReader class are used. The object of BufferedReader “br” is useful to take input values given by the user. This line print some text to give an indication to the user like ”Enter the file name:”. To print text “println()” function is used. Here “readLine()” method is used to take input and store it, in strFileName and strFilePath. Here object of FileOutputStream class is created and as a parameter, file path and name are given to the constructor. In this line of code “.txt” is a format of the file. You can change it as per need. The object of FileOutputStream class is necessary to call methods provided in its class. For example, if the user wants to store some text in a newly created file programmatically then, the write() method is helpful. Lastly, enclosed by “try{ }” block. Because, readLine() method generates exception. So to handle that exception try, catch block is used. Output: It will be the same as the previous one because just the approach to create a new file has changed the rest of the file name and the directory where it is added remains the same.

Added file name : newFile.txt Added file name directory : /Users/mayanksolanki/Desktop/Folder/


Referensi