Home Java javaTutorial File reading and writing techniques and applications implemented in Java

File reading and writing techniques and applications implemented in Java

Jun 18, 2023 am 08:34 AM
Applications File handling skills java file reading and writing

Java is a high-level programming language with very powerful file reading and writing functions. In this article, we will introduce the techniques and applications of Java file reading and writing.

1. Basics of Java file reading and writing

1.1 Reading files

The most commonly used method of reading files in Java is to use the BufferedReader class. The following is a simple example:

try{
    BufferedReader br = new BufferedReader(new FileReader("input.txt"));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch(IOException e){
    e.printStackTrace();
}
Copy after login

In this code, we first create a BufferedReader object, which reads the input.txt file using the FileReader class. We then read each line in the file and print it to the console.

1.2 Writing files

The most commonly used method of writing files in Java is to use the PrintWriter class. The following is a simple example:

try{
    PrintWriter pw = new PrintWriter("output.txt");
    pw.println("Hello, world!");
    pw.close();
} catch(IOException e){
    e.printStackTrace();
}
Copy after login

In this code, we first create a PrintWriter object, which will write the output to the output.txt file. Then we write a line of "Hello, world!" string to the file, and finally close the PrintWriter object.

1.3 Binary file reading and writing

In addition to text files, Java can also read and write binary files. The following is a simple example:

try{
    FileInputStream fis = new FileInputStream("input.bin");
    int data = fis.read();
    while (data != -1) {
        System.out.println(data);
        data = fis.read();
    }
    fis.close();
} catch(IOException e){
    e.printStackTrace();
}
Copy after login

In this code, we first create a FileInputStream object, which opens the input.bin file in binary mode. We then read the data from the file byte by byte and print it to the console. Finally we close the FileInputStream object.

2. Java file reading and writing skills

2.1 File character encoding

When processing text files in Java, you need to pay special attention to the character encoding of the file. If the file's encoding is not Java's default UTF-8 encoding, you need to use an appropriate encoder to read or write the file. The following is an example of reading a UTF-16 encoded file:

try{
    BufferedReader br = new BufferedReader(new InputStreamReader(
            new FileInputStream("input.txt"), "UTF-16"));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();
} catch(IOException e){
    e.printStackTrace();
}
Copy after login

In this code, we read the input.txt file by converting the FileInputStream object to an InputStreamReader object and specifying the UTF-16 encoder. It is important to note that reading a text file using an incorrect encoder may produce strange characters or encoding errors, so be sure to pay attention to the encoding of the file.

2.2 Reading and writing large files

You need to pay special attention to memory usage when processing large files. If you read the entire file into memory at once, you may cause a memory leak or program crash. So you can use Java NIO (New I/O) to read large files line by line. The following is an example of reading a large file:

try{
    RandomAccessFile raf = new RandomAccessFile("input.txt", "r");
    FileChannel fc = raf.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    while (fc.read(buf) != -1) {
        buf.flip();
        byte[] bytes = new byte[buf.limit()];
        buf.get(bytes);
        System.out.print(new String(bytes, Charset.forName("UTF-8")));
        buf.clear();
    }
    fc.close();
    raf.close();
} catch(IOException e){
    e.printStackTrace();
}
Copy after login

In this code, we first create a RandomAccessFile object and use the RandomAccessFile object to create a FileChannel object. Then we create a ByteBuffer object with a size of 1024 bytes. Then we use the FileChannel object to read the data into the ByteBuffer object, use the ByteBuffer object to convert the data into a byte array, and use the UTF-8 encoder to convert the byte array into a string. Finally we clear the ByteBuffer object so that we can read data next time.

2.3 Writing large files

When dealing with large files, special attention needs to be paid to dividing the file into appropriate sizes and writing line by line. The following is an example of writing a large file:

try{
    PrintWriter pw = new PrintWriter(new File("output.txt"));
    for (int i = 0; i < 1000000; i++) {
        pw.println("Line #" + i);
        if (i % 10000 == 0) {
            pw.flush();
        }
    }
    pw.close();
} catch(IOException e){
    e.printStackTrace();
}
Copy after login

In this code, we first create a PrintWriter object, which will write the output to the output.txt file. Then we write 1,000,000 rows of data in a loop and flush the buffer every 10,000 rows to write the data to disk. Finally we close the PrintWriter object.

3. Java file reading and writing applications

3.1 File copy

One of the most commonly used applications of Java file reading and writing functions is file copying. The following is a simple file copy example:

try{
    FileInputStream fis = new FileInputStream("input.txt");
    FileOutputStream fos = new FileOutputStream("output.txt");
    byte[] buffer = new byte[1024];
    int count;
    while ((count = fis.read(buffer)) != -1) {
        fos.write(buffer, 0, count);
    }
    fis.close();
    fos.close();
} catch(IOException e){
    e.printStackTrace();
}
Copy after login

In this code, we first create a FileInputStream object to read the input.txt file. Then we created a FileOutputStream object to write data to the output.txt file. Next we create a byte array buffer to copy the file block by block. Finally we loop through each piece of data in the file and write it to the output file.

3.2 File Hash Value Calculation

The Java file read and write function can also be used to calculate the hash value (Hash) of the file. The following is an example of calculating the hash value of a file:

try{
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    FileInputStream fis = new FileInputStream("input.txt");
    byte[] buffer = new byte[1024];
    int count;
    while ((count = fis.read(buffer)) != -1) {
        md.update(buffer, 0, count);
    }
    fis.close();
    byte[] digest = md.digest();
    System.out.println(DatatypeConverter.printHexBinary(digest));
} catch(IOException | NoSuchAlgorithmException e){
    e.printStackTrace();
}
Copy after login

In this code, we first create a MessageDigest object and use the SHA-256 encryption algorithm. Then we created a FileInputStream object to read the input.txt file. Then we create a byte array buffer and loop through each piece of data in the file and update it into the MessageDigest object. Finally we close the FileInputStream object and use the MessageDigest object to calculate the hash value of the file and output the calculation result to the console in the form of a hexadecimal string.

Conclusion

Java file reading and writing functions are very powerful. Developers can flexibly use various techniques to handle different reading and writing needs, such as processing file encoding, large file reading and writing, file copying and Hash value calculation etc. Therefore, mastering Java file reading and writing skills and applications can help improve development efficiency and code quality.

The above is the detailed content of File reading and writing techniques and applications implemented in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Keyword extraction algorithm and application examples implemented in Java Keyword extraction algorithm and application examples implemented in Java Jun 18, 2023 pm 12:14 PM

Keyword extraction algorithms and application examples implemented in Java With the advent of the Internet era, massive text data has caused great difficulties for people to obtain and analyze. Therefore, it is necessary to conduct research and application of natural language processing technologies such as keyword extraction. Keyword extraction refers to extracting words or phrases from a piece of text that best represent the topic of the text, providing support for tasks such as text classification, retrieval, and clustering. This article introduces several keyword extraction algorithms and application examples implemented in Java. 1. TF-IDF algorithm TF-IDF is a

Redis methods and application examples for implementing asynchronous queues Redis methods and application examples for implementing asynchronous queues May 11, 2023 pm 03:27 PM

Redis is a high-performance memory-based key-value storage database. It not only supports storing key-value pairs, but also supports some complex data structures, such as List, Set, SortedSet, and Hash. The List data structure is very suitable as a data structure for asynchronous queues because it supports inserting and deleting elements at both ends. This article will introduce how to use Redis to implement asynchronous queues and give an application example. 1. How Redis implements asynchronous queue Lis in Redis

Redis methods and application examples for implementing distributed queues Redis methods and application examples for implementing distributed queues May 11, 2023 pm 05:14 PM

As a high-performance in-memory database, Redis is widely used in distributed systems. Among them, as one of the important components of distributed systems, distributed queues are undoubtedly very important. This article will focus on the distributed characteristics of Redis and introduce the methods and application examples of Redis to implement distributed queues. 1. Redis distributed features As an in-memory database, Redis has excellent performance in caching, persistence and other aspects. In distributed systems, Redis also has a very prominent feature, that is, Re

Redis methods and application examples for realizing distributed coordination Redis methods and application examples for realizing distributed coordination May 11, 2023 pm 03:27 PM

Redis methods and application examples for implementing distributed coordination In distributed systems, coordination between nodes is a key issue. Traditional solutions usually use a central node to coordinate other nodes, but this will bring problems such as single points of failure and performance bottlenecks. In recent years, Redis, as a high-performance in-memory database, has been increasingly widely used. In Redis, its data structure and command set can be used to implement distributed coordination functions, thereby achieving a highly available and high-performance distributed system. This article will introduce Re

Five must-know cases to understand canvas JS technology Five must-know cases to understand canvas JS technology Jan 17, 2024 am 08:05 AM

CanvasJS technology application examples: Five cases you have to know Introduction: The emergence of HTML5 has brought new possibilities to web development, especially the Canvas element, which provides a powerful way to draw graphics and animations on the page. ability. Combined with the power of JavaScript, developers can use Canvas to achieve a variety of cool effects and interactions, and improve user experience. This article will introduce five amazing CanvasJS application examples and provide relevant

Application examples of Redis in data visualization Application examples of Redis in data visualization May 11, 2023 pm 04:29 PM

Application examples of Redis in data visualization In recent years, data visualization has become one of the important links in data analysis and decision-making. Through visualization tools, data analysts and decision-makers can understand the data situation more clearly and intuitively, so as to make better decisions. The challenges brought by big data also prompt us to continue exploring and innovating in data visualization. This article will introduce the application examples of Redis in data visualization. Through these examples, we can better understand the ecology and value of Redis in data visualization.

Application examples of Redis in recommendation systems Application examples of Redis in recommendation systems May 12, 2023 am 11:21 AM

Application examples of Redis in recommendation systems With the development of the Internet and the explosive growth of information, information overload has become a major problem affecting people's access to information. Therefore, the recommendation system emerged as the times require. It can predict user behavior through algorithms and provide personalized recommendation services, which greatly improves user experience and product profits. The implementation of the recommendation system requires a large amount of data storage, processing and calculation, and Redis is an excellent solution. Redis is a high-performance NoSQL database,

Namespace configuration and application examples in PHP Namespace configuration and application examples in PHP Jun 25, 2023 am 08:32 AM

PHP is a highly flexible programming language with a wide range of applications. In PHP development, in order to avoid naming conflicts and improve the readability and maintainability of code, PHP introduces the concept of namespace. Namespaces help developers use the same class or function name in the same project without conflict. This article will introduce how to configure namespaces in PHP and common application examples. 1. How to configure the PHP namespace. Declare the namespace in PHP by using namespa at the top of the file.

See all articles