Home  >  Article  >  Java  >  File handling in Java

File handling in Java

WBOY
WBOYforward
2023-08-18 15:45:12966browse

In Java programming, the File class from the java.io package plays a key role in file operations. By creating an object of this class and specifying the name of the file, we can efficiently manipulate files.

But why is file handling so important?

File handling is of great significance in programming languages ​​as it enables us to store program output in files and perform various operations on them. Basically, file processing involves the act of reading and writing data from files.

You use streams to perform input/output (I/O) operations on files. It is very important to understand how file operations are done in Java, so become familiar with this concept.

Streams in Java

Java has two types of streams: input streams are used to read data, and output streams are used to write data.

Input stream

Java's InputStream class serves as the superclass of all input streams. Input streams are responsible for reading data from various input devices, such as keyboards or network connections. Although InputStream is an abstract class and not directly useful by itself, its subclasses are used for reading data.

Some noteworthy subclasses of the InputStream class include:

  • AudioInputStream

  • ByteArrayInputStream

  • FileInputStream

  • FilterInputStream

  • StringBufferInputStream

  • ObjectInputStream

Output stream

On the other hand, output streams are responsible for writing data to various output devices, such as monitors or files. The OutputStream class serves as an abstract superclass representing an output stream. Similar to InputStream, OutputStream is also abstract and requires the use of its subclasses to write data.

Some noteworthy subclasses of the OutputStream class include:

  • ByteArrayOutputStream

  • FileOutputStream

  • StringBufferOutputStream

  • ObjectOutputStream

  • DataOutputStream

  • PrintStream

According to the type of data processed, streams can be divided into two types: byte stream and character stream.

File methods in Java

The File class in Java provides a set of useful methods for working with files. The following are several important methods of the File class:

Method name

Meaning of method

Return type

canRead()

Check if the file is readable

Boolean value

canWrite()

Check if you can write to the file

Boolean value

createNewFile()

This method creates an empty file

Boolean value

delete()

Help you delete files

Boolean value

exists()

Check if the file exists

Boolean value

length()

This method returns the total size of the file (in bytes)

long

getName()

Return the name of the file

String

list()

Return the array of files in the directory

String[]

mkdir()

This function creates a new directory

Boolean value

getAbsolutePath()

This function returns the absolute path name of a file

String

Create a file

In Java, the CreateNewFile() method is used to create a new file. When a new file is successfully created, the output will return true. In all other cases it will return false.

createNewFile()

Below is sample code for this operation.

algorithm

  • Step 1: First, we need to import the necessary java classes: "java io file" and "java io io exception".

  • Step 2: Next we will create a public class. Here we have selected a FileExample.

  • Step 3: Define the main method in the class.

  • Step 4: Start a try-catch block for exception management.

  • Step 5: Create a new file object named "myfile.txt" inside the try block.

  • Step 6: Use its "Create New File" method to actually create the file.

  • Step 7: We will use if else statement to check if this process was successful.

  • Step 8: If the creation is successful, we will print "File Created" followed by the file name obtained through the file.getName() method.

  • Step 9: Otherwise, if the file already exists, we will print "File Already Exists".

  • Step 10: End the if-else statement.

  • Step 11: End the try block.

  • Step 12: Catch any IOException that may occur and print the error message.

  • Step 13: Print the stack trace of the exception.

  • Step 14: As a final step, let’s exit the program

The Chinese translation of

Example

is:

Example

import java.io.File;
import java.io.IOException;

public class FileExample {
    public static void main(String[] args) {
        try {
            File file = new File("myfile.txt");
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output

File created: myfile.txt

Read from file

In Java, there are many ways to read and write text files. Here are several ways to read plain text files:

  • Using the BufferedReader class: By buffering data, the BufferedReader class allows efficient reading. It goes through the file line by line.

  • Using the Scanner class: The Scanner class includes methods for processing and reading input. It is able to read text files line by line.

  • Use the FileReader class: The FileReader class is used to read character files. It reads the file character by character or by the given buffer size.

  • Read the entire file into a list: You can use Java 8's streaming API to read the entire file into a list of strings, where each line is a different element .

  • Reading a text file as a string: You can use Java 8's Streaming API to read the entire file content as a single string.

Write to file

To write text to a file, you can use the FileWriter class. It allows you to write data to files.

The translation of

FileWriter()

is:

FileWriter()

Algorithm:

  • Step 1: Create a public class named FileExample.

  • Step 2: Define the main method in the class.

  • Step 3: Start a try-catch block for exception handling.

  • Step 4: Within the try block, create a new FileWriter object named writer using the file name "myfile.txt".

  • Step 5: Use the write() method of the writer object to write the text "Files in Java are seriously good!!".

  • Step 6: Use the close() method to close the writer object.

  • Step 7: Print "Successfully written." to indicate successful writing.

  • Step 8: End the try block.

  • Step 9: Catch any IOException that may occur and print the error message.

  • Step 10: Print the stack trace of the exception.

  • Step 11: Close the program

The Chinese translation of

Example

is:

Example

import java.io.FileWriter;
import java.io.IOException;

public class FileExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("myfile.txt");
            writer.write("Files in Java are seriously good!!");
            writer.close();
            System.out.println("Successfully has been written.");
        } catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output

Successfully has been written.

Delete Files

To delete a file, you can use the delete() method of the File class. It will return true if the file was successfully deleted.

delete()

is translated as:

delete()

This Java code demonstrates the use of File class for file deletion. It creates a File object named "myfile.txt". If delete() succeeds, the name of the deleted file will be displayed. If it fails, a failure message will be displayed. The output confirms the successful deletion of "myfile.txt".

algorithm

  • Step 1: Create a new File object named file.

  • Step 2: Pass the file name to be deleted as a parameter. In this example, the file name we are using is "myfile.txt".

  • Step 3: Write an if statement to verify whether 'delete()' is successfully executed in this file

  • Step 4: If you successfully deleted the file, you can use file.getName() to output "The deleted file was:" along with the name of the file.

  • Step 5: If our deletion attempt fails, our output will be "Unable to delete file."

  • Step 6: Finally, end the if statement.

  • Step 7: Needless to say, complete the procedure.

Example

的中文翻译为:

示例

import java.io.File;

public class FileExample {
    public static void main(String[] args) {
        File file = new File("myfile.txt");
        if (file.delete()) {
            System.out.println("The deleted file is: " + file.getName());
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}

输出

Failed to delete the file.

结论

在Java中,文件处理对于操作文件和执行各种操作非常重要。File类允许我们有效地创建对象并处理文件。对于文件的输入/输出(I/O)操作,您可以使用流。在Java中,您可以使用createNewFile()、delete()和length()方法来处理文件,如本文所讨论的。

BufferedReader、Scanner和FileReader方法有助于读取文本文件。使用FileWriter可以将内容写入文件。在Java中,有效处理文件对于高效的数据存储和恢复至关重要。

The above is the detailed content of File handling in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete