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

File reading and writing techniques and applications implemented in Java

王林
王林Original
2023-06-18 08:34:371713browse

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