


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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment