SoFunction
Updated on 2025-04-10

Java input and output streaming method (file copying)

Java input and output stream (file copy)

Java's input and output streams are mechanisms used for data input and output. They provide a flexible way to read and write various types of data such as files, network connections, memory buffers, etc.

The use of input and output streams mainly involves the following aspects

  • File Input and Output: Use the file Input and Output stream to read and write files. For example, the FileInputStream and FileOutputStream classes can be used to read and write binary files, while the FileReader and FileWriter classes can handle text files.
  • Keyboard input: Java provides streams for getting input from the keyboard. The console input can be read using the standard input stream() and InputStreamReader classes.
  • Network input and output: The Socket class and ServerSocket class in Java are used to build network connections and transmit data through input and output streams.
  • Memory Buffer: Java provides ByteArrayInputStream and ByteArrayOutputStream classes to create input and output streams in memory, so that data can be read and written in memory.

When using input and output streams, you need to pay attention to the following points

  • Close Stream: After the operation is completed, the input and output stream should be explicitly closed to free up resources. You can use the try-with-resources statement block to ensure the normal shutdown of the stream.
  • Exception handling: When using the input and output stream, exceptions such as IOException may be thrown. These exceptions should be handled appropriately and error handling should be performed according to actual conditions.
  • Buffer: To improve read and write efficiency, buffers can be used to process input and output streams. The BufferedReader and BufferedWriter classes provide efficient buffered read and write functions.
  • Use appropriate streams appropriately: Select the appropriate input and output streams according to actual needs. For example, if you need to process text files, using Reader and Writer classes can better support character encoding and text processing.

In short, Java's input and output streams provide a convenient and flexible way to read and write data. Through reasonable use and effective resource management, we can achieve various input and output operations.

Copying of files

1. Create input stream and output stream objects:

First, we need to create an input stream for reading the source file and an output stream for writing to the target file.

You can use the FileInputStream and FileOutputStream classes to create corresponding input and output stream objects.

FileInputStream inputStream = null;
FileOutputStream outputStream = null;

2. Open the source and target files:

Use the input stream to open the source file, and use the output stream to create or open the target file. Here you need to specify the source file path and the target file path.

String sourceFilePath = "path/to/source/file";
String targetFilePath = "path/to/target/file";

try {
    inputStream = new FileInputStream(sourceFilePath);
    outputStream = new FileOutputStream(targetFilePath);
} catch (IOException e) {
    // Exception handling}

3. Read and write data:

Read the data in the source file by looping and writing it to the target file.

You can use the input streamread()Method reads a byte and then uses the output stream'swrite()Method writes this byte to the target file.

int bytesRead;

try {
    byte[] buffer = new byte[1024]; // Create a buffer    while ((bytesRead = (buffer)) != -1) {
        (buffer, 0, bytesRead); // Write the read data to the target file    }
} catch (IOException e) {
    // Exception handling}

4. Close the flow:

After copying is complete, close the input and output stream to free up resources.

try {
    if (inputStream != null) {
        ();
    }
    if (outputStream != null) {
        ();
    }
} catch (IOException e) {
    // Exception handling}

The above is a simple file copy example that uses input and output streams to enable data reading and writing.

Complete code

import ;
import ;
import ;

public class FileCopyExample {
    public static void main(String[] args) {
        String sourceFilePath = "path/to/source/file";
        String targetFilePath = "path/to/target/file";

        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            inputStream = new FileInputStream(sourceFilePath);
            outputStream = new FileOutputStream(targetFilePath);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = (buffer)) != -1) {
                (buffer, 0, bytesRead);
            }

            ("File copy successfully!");
        } catch (IOException e) {
            ("File copy failed:" + ());
        } finally {
            try {
                if (inputStream != null) {
                    ();
                }
                if (outputStream != null) {
                    ();
                }
            } catch (IOException e) {
                ("Closing churn failed:" + ());
            }
        }
    }
}

Please replacesourceFilePathandtargetFilePathFor the actual source file path and the target file path.

When running the code, it reads the contents of the source file and writes it to the target file.

If the file is copied successfully, "File copy is copied successfully!" will be output; if any exceptions appear, an error message will be output.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.