File Handling in JAVA!!
File Handling in Java!
File handling is an essential part of any programming language. Using files, a program can store data on a storage device. To perform various actions on a file, such as read, write, and so on, file handling is required.
- File handling is defined as reading from a file and writing to a file. We can use the File class in JAVA to create a file object. The package java.io contains a File class to work and handle different formats of files.
- If you want to use the File class, you need to create an object of the File class and provide the name of the file or pathname. Using file class we can access metadata of files such as file name, file size, permissions, type of file, etc.
What is a Stream in Java?
A stream is a sequence of data. It is also defined as a sequence of bytes. It can be used to represent either an input source or a destination. The source and destination can be disk files, arrays, text files, etc. The input stream reads or retrieves data from a source, whereas the output stream writes data to a destination. There are two types of streams:
Byte stream:
- Byte Stream is used for performing read and write operations with byte data.
- The two classes mostly used in byte stream are FileInputStream and FileOutputStream.
Character stream:
- Character Stream is used to performing read and write operations with character data.
- There are many character stream classes available, but the most commonly used classes include FileWriter and FileReader.
What are the File class methods in Java?
canRead()
This file class method checks whether the file is readable or not and returns a Boolean value i.e., true or false.
canWrite()
This is a file class method that checks whether the file is writable or not and returns a Boolean value i.e., true or false.
exists()
It is a file class method used to check whether the given file is present or not and returns a boolean value.
createNewFile()
When we want to create a new empty file, use this file class method. It returns a Boolean value.
delete()
It is a file class method used for deleting a file and returns a Boolean value.
getAbsolutePath()
This method is used to return the absolute pathname of the file.getName()
It is a method used to return a string value which is the name of the file.
list()
It returns an array of strings representing all the files in the directory.
length()
This method of the file class returns the file’s size in bytes.
mkdir()
It is a method of file class that is used to create a new directory.
What are the file operations in Java?
- Creating a file
- Writing data to a file
- Reading data from a file
- Deleting a file
- Getting information of a file
Comments
Post a Comment