All file programs in java

Java File Class

The File class of the java.io package is used to perform various operations on files and directories.

There is another package named java.nio that can be used to work with files. However, in this tutorial, we will focus on the java.io package.

File and Directory

A file is a named location that can be used to store related information. For example,

main.java is a Java file that contains information about the Java program.

A directory is a collection of files and subdirectories. A directory inside a directory is known as subdirectory.

Create a Java File Object

To create an object of File , we need to import the java.io.File package first. Once we import the package, here is how we can create objects of file.

// creates an object of File using the path File file = new File(String pathName); 

Here, we have created a file object named file . The object can be used to work with files and directories.

Note: In Java, creating a file object does not mean creating a file. Instead, a file object is an abstract representation of the file or directory pathname (specified in the parenthesis).

Java File Operation Methods

Operation Method Package
To create file createNewFile() java.io.File
To read file read() java.io.FileReader
To write file write() java.io.FileWriter
To delete file delete() java.io.File

Java create files

To create a new file, we can use the createNewFile() method. It returns

  • true if a new file is created.
  • false if the file already exists in the specified location.

Example: Create a new File

// importing the File class import java.io.File; class Main < public static void main(String[] args) < // create a file object for the current location File file = new File("newFile.txt"); try < // trying to create a file based on the object boolean value = file.createNewFile(); if (value) < System.out.println("The new file is created."); >else < System.out.println("The file already exists."); >> catch(Exception e) < e.getStackTrace(); >> > 

In the above example, we have created a file object named file . The file object is linked with the specified file path.

File file = new File("newFile.txt"); 

Here, we have used the file object to create the new file with the specified path.

If newFile.txt doesn’t exist in the current location, the file is created and this message is shown.

However, if newFile.txt already exists, we will see this message.

Java read files

To read data from the file, we can use subclasses of either InputStream or Reader.

Example: Read a file using FileReader

Suppose we have a file named input.txt with the following content.

This is a line of text inside the file. 

Now let’s try to read the file using Java FileReader .

// importing the FileReader class import java.io.FileReader; class Main < public static void main(String[] args) < char[] array = new char[100]; try < // Creates a reader using the FileReader FileReader input = new FileReader("input.txt"); // Reads characters input.read(array); System.out.println("Data in the file:"); System.out.println(array); // Closes the reader input.close(); >catch(Exception e) < e.getStackTrace(); >> > 
Data in the file: This is a line of text inside the file. 

In the above example, we have used created an object of FileReader named input. It is now linked with the input.txt file.

FileReader input = new FileReader("input.txt"); 

To read the data from the input.txt file, we have used the read() method of FileReader .

Читайте также:  Php print all variables

Java write to files

To write data to the file, we can use subclasses of either OutputStream or Writer.

Example: Write to file using FileWriter

// importing the FileWriter class import java.io.FileWriter; class Main < public static void main(String args[]) < String data = "This is the data in the output file"; try < // Creates a Writer using FileWriter FileWriter output = new FileWriter("output.txt"); // Writes string to the file output.write(data); System.out.println("Data is written to the file."); // Closes the writer output.close(); >catch (Exception e) < e.getStackTrace(); >> > 
Data is written to the file. 

In the above example, we have created a writer using the FileWriter class. The writer is linked with the output.txt file.

FileWriter output = new FileWriter("output.txt"); 

To write data to the file, we have used the write() method .

Here when we run the program, the output.txt file is filled with the following content.

This is the data in the output file. 

Java delete files

We can use the delete() method of the File class to delete the specified file or directory. It returns

Note: We can only delete empty directories.

Example: Delete a file

import java.io.File; class Main < public static void main(String[] args) < // creates a file object File file = new File("file.txt"); // deletes the file boolean value = file.delete(); if(value) < System.out.println("The File is deleted."); >else < System.out.println("The File is not deleted."); >> > 

In the above example, we have created an object of File named file. The file now holds the information about the specified file.

File file = new File("file.txt"); 

Here we have used the delete() method to delete the file specified by the object.

Table of Contents

Источник

File Handling in Java

In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file.

Why File Handling is Required?

  • File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it.
  • In simple words, file handling means reading and writing data to a file.

Java

In Java, the concept Stream is used in order to perform I/O operations on a file. So at first, let us get acquainted with a concept known as Stream in Java.

Streams in Java

  • In Java, a sequence of data is known as a stream.
  • This concept is used to perform I/O operations on a file.
  • There are two types of streams :

1. Input Stream:

The Java InputStream class is the superclass of all input streams. The input stream is used to read data from numerous input devices like the keyboard, network, etc. InputStream is an abstract class, and because of this, it is not useful by itself. However, its subclasses are used to read data.

There are several subclasses of the InputStream class, which are as follows:

  1. AudioInputStream
  2. ByteArrayInputStream
  3. FileInputStream
  4. FilterInputStream
  5. StringBufferInputStream
  6. ObjectInputStream

Creating an InputStream

// Creating an InputStream InputStream obj = new FileInputStream();

Here, an input stream is created using FileInputStream.

Note: We can create an input stream from other subclasses as well as InputStream.

Methods of InputStream

S No. Method Description
1 read() Reads one byte of data from the input stream.
2 read(byte[] array)() Reads byte from the stream and stores that byte in the specified array.
3 mark() It marks the position in the input stream until the data has been read.
4 available() Returns the number of bytes available in the input stream.
5 markSupported() It checks if the mark() method and the reset() method is supported in the stream.
6 reset() Returns the control to the point where the mark was set inside the stream.
7 skips() Skips and removes a particular number of bytes from the input stream.
8 close() Closes the input stream.
Читайте также:  Html table in container

2. Output Stream:

The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream is an abstract superclass that represents an output stream. OutputStream is an abstract class and because of this, it is not useful by itself. However, its subclasses are used to write data.

There are several subclasses of the OutputStream class which are as follows:

  1. ByteArrayOutputStream
  2. FileOutputStream
  3. StringBufferOutputStream
  4. ObjectOutputStream
  5. DataOutputStream
  6. PrintStream

Creating an OutputStream

// Creating an OutputStream OutputStream obj = new FileOutputStream();

Here, an output stream is created using FileOutputStream.

Note: We can create an output stream from other subclasses as well as OutputStream.

Methods of OutputStream

S. No. Method Description
1. write() Writes the specified byte to the output stream.
2. write(byte[] array) Writes the bytes which are inside a specific array to the output stream.
3. close() Closes the output stream.
4. flush() Forces to write all the data present in an output stream to the destination.

Based on the data type, there are two types of streams :

1. Byte Stream:

This stream is used to read or write byte data. The byte stream is again subdivided into two types which are as follows:

  • Byte Input Stream: Used to read byte data from different devices.
  • Byte Output Stream: Used to write byte data to different devices.

2. Character Stream:

This stream is used to read or write character data. Character stream is again subdivided into 2 types which are as follows:

  • Character Input Stream: Used to read character data from different devices.
  • Character Output Stream: Used to write character data to different devices.

Owing to the fact that you know what a stream is, let’s polish up File Handling in Java by further understanding the various methods that are useful for performing operations on the files like creating, reading, and writing files.

Java File Class Methods

The following table depicts several File Class methods:

Method Name Description Return Type
canRead() It tests whether the file is readable or not. Boolean
canWrite() It tests whether the file is writable or not. Boolean
createNewFile() It creates an empty file. Boolean
delete() It deletes a file. Boolean
exists() It tests whether the file exists or not. Boolean
length() Returns the size of the file in bytes. Long
getName() Returns the name of the file. String
list() Returns an array of the files in the directory. String[]
mkdir() Creates a new directory. Boolean
getAbsolutePath() Returns the absolute pathname of the file. String

Let us now get acquainted with the various file operations in Java.

File operations in Java

The following are the several operations that can be performed on a file in Java :

Now let us study each of the above operations in detail.

Читайте также:  A viewtopic php включает

1. Create a File

  • In order to create a file in Java, you can use the createNewFile() method.
  • If the file is successfully created, it will return a Boolean value true and false if the file already exists.

Following is a demonstration of how to create a file in Java :

Источник

File Handling in Java

Hi guys, welcome back. In this module, I will be discussing file handling in Java Programming. After reading this module, you will get to know file handling operations in Java. Let’s know about Java file handling without any further delay.

File Handling in Java

File Handling in Java

File handling in Java 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 reading, writing, and so on, file handling is required.

file handling in Java 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.

// importing all the classes of java.io import java.io.*; class FileHandle < public static void main(String[] arr) < // an object of File class is created. File f=new File("demo.txt"); >>

Note: You can give an absolute pathname if you are not in the current working directory.

You can also use import java.io.File instead of using import java.io.* to import the File class in Java. Now, let’s know about streams because Java uses Streams to perform input-output (I/O) operations on a file.

What is a Stream in Java?

A stream in Java 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 in Java Programming

Byte Stream is used to perform read and write operations with byte data. A byte stream file handling in Java process is defined as when the given input is executed using byte data. There are many classes provided related to byte streams but the most often used classes are FileInputStream and FileOutputStream.

import java.io.*; public class FileHandle < public static void main(String []arr) throws IOException< FileInputStream fin=new FileInputStream("source_file.txt"); FileOutputStream fout=new FileOutputStream("destination_file.txt"); int character; while((character=fin.read())!=-1) < System.out.print((char)character); // writing to destination file fout.write((char)character); >// closing source_file.txt fin.close(); // closing destination_file.txt fout.close(); > >

In the above example, we are reading data from the source file and writing data to a destination. -1 indicates the end of the file. So, reading from the source file will be stopped when -1 is encountered.

Character stream in Java Programming

Character Stream in Java programming is used to perform read and write operations with character data. The file-handling process with a character stream is the process of executing input data with characters. There are many character stream classes available, but the most commonly used classes include FileWriter and FileReader.

Now, let’s discuss some of the File class methods in Java Programming.

Источник

Оцените статью