search
HomeJavajavaTutorialMaster file operation skills in Java development: implement data persistence function

Master file operation skills in Java development: implement data persistence function

Nov 20, 2023 am 10:23 AM
File operationsData persistencejava development

Master file operation skills in Java development: implement data persistence function

In the Java development process, file operations are a very common and important part. Whether it is reading configuration files, storing user data, or exporting reports and log records, file operations are indispensable skills. This article will share some file operation techniques to achieve data persistence.

1. File reading and writing
In Java, you can use the File class to create, delete, rename, and obtain file attributes and other operations. For reading and writing files, you can use FileReader, FileWriter, BufferedReader, BufferedWriter and other classes to achieve. The following is a simple example:

import java.io.*;

public class FileOperationExample {
    public static void main(String[] args) {
        try {
            // 文件写入
            FileWriter writer = new FileWriter("data.txt");
            writer.write("Hello World!");
            writer.close();

            // 文件读取
            FileReader reader = new FileReader("data.txt");
            BufferedReader br = new BufferedReader(reader);

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            br.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we first use FileWriter to write a string to a file named "data.txt". Then, use FileReader and BufferedReader to read the contents of the file and print the contents line by line. Finally, remember to close the associated file stream to free up resources.

2. CSV file operation
CSV (Comma-Separated Values) format is a common file format, usually used to store tabular data. In Java, you can use classes such as CSVReader and CSVWriter to read and write CSV files. The following is an example:

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.*;

public class CSVFileOperationExample {
    public static void main(String[] args) {
        try {
            // CSV文件写入
            CSVWriter writer = new CSVWriter(new FileWriter("data.csv"));

            String[] record1 = {"John", "Doe", "35"};
            String[] record2 = {"Jane", "Smith", "28"};
            String[] record3 = {"Tom", "Lee", "42"};

            writer.writeNext(record1);
            writer.writeNext(record2);
            writer.writeNext(record3);

            writer.close();

            // CSV文件读取
            CSVReader reader = new CSVReader(new FileReader("data.csv"));

            String[] line;
            while ((line = reader.readNext()) != null) {
                System.out.println(String.join(", ", line));
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we use the third-party library opencsv to operate CSV files. First, use CSVWriter to write three records to a CSV file named "data.csv", using commas as the separator between fields. Then, use the CSVReader and readNext() methods to read each line in the file, and finally print the fields of each line in comma-separated form.

3. Serialization and Deserialization
Java provides object serialization (Serialization) and deserialization (Deserialization) mechanisms, which can convert objects into byte streams for storage, or from characters Throttle revert to object. In this way, objects can be stored or transferred in the form of files. The following is an example:

import java.io.*;

class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        try {
            // 对象序列化
            Person person = new Person("John Doe", 35);
            FileOutputStream fileOut = new FileOutputStream("person.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();

            // 对象反序列化
            FileInputStream fileIn = new FileInputStream("person.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Person deserializedPerson = (Person) in.readObject();
            in.close();
            fileIn.close();

            System.out.println("Name: " + deserializedPerson.name);
            System.out.println("Age: " + deserializedPerson.age);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

In this example, we define a class named Person that implements the Serializable interface so that the class can be serialized. We then created a Person object and serialized it into a file named "person.ser". Next, we deserialize the Person object from the file and print out the object's properties.

In actual development, file operations are very common operations. By mastering skills such as file reading and writing, CSV file operations, serialization and deserialization, we can easily implement the data persistence function, thereby realizing richer application scenarios. I hope this article will be helpful to your file operations in Java development.

The above is the detailed content of Master file operation skills in Java development: implement data persistence function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why does the browser fail to correctly process the 401 status code when developing a WebSocket server using Netty?Why does the browser fail to correctly process the 401 status code when developing a WebSocket server using Netty?Apr 19, 2025 pm 07:21 PM

在使用Netty开发WebSocket服务器时,可能会遇到浏览器在尝试连接时未能正确处理服务器返回的401状态码的情况。 �...

Java compilation failed: What should I do if the javac command cannot generate the class file?Java compilation failed: What should I do if the javac command cannot generate the class file?Apr 19, 2025 pm 07:18 PM

Java compilation failed: Running window javac command cannot generate class file Many Java beginners will encounter this problem during the learning process: running window...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development?How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development?Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

Java compilation error: How do package declaration and access permissions change after moving the class file?Java compilation error: How do package declaration and access permissions change after moving the class file?Apr 19, 2025 pm 07:12 PM

Packages and Directories in Java: The logic behind compiler errors In Java development, you often encounter problems with packages and directories. This article will explore Java in depth...

Is JWT suitable for dynamic permission change scenarios?Is JWT suitable for dynamic permission change scenarios?Apr 19, 2025 pm 07:06 PM

JWT and Session Choice: Tradeoffs under Dynamic Permission Changes Many Beginners on JWT and Session...

How to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?How to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?Apr 19, 2025 pm 07:03 PM

How to correctly configure apple-app-site-association file in Baota nginx? Recently, the company's iOS department sent an apple-app-site-association file and...

What are the differences in the classification and implementation methods of the two consistency consensus algorithms?What are the differences in the classification and implementation methods of the two consistency consensus algorithms?Apr 19, 2025 pm 07:00 PM

How to understand the classification and implementation methods of two consistency consensus algorithms? At the protocol level, there has been no new members in the selection of consistency algorithms for many years. ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.