search
HomeJavajavaTutorialFile 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
ApplicationsFile handling skillsjava 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();
}

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();
}

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();
}

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();
}

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();
}

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();
}

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();
}

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();
}

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
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor