Java uses file input and output stream to copy all files in a folder to another folder

1、 Basic objectives

Use java to complete the following operations:

Copy all files in one folder to another folder. For example, there are two folders A and B in disk F:

f: / a contains a pile of files. After running the Java program, all files will be copied to F: / B and renamed. Rename all files_ If there is a folder in it, the folder will not be renamed, and the files in it will be renamed. Similarly, rename will be added before all files_ Prefix of:

2、 Production process

1. First, the main function is very simple, that is, it calls the CopyFolder function in the filetest class above

It is worth noting that in Java, F: / A is no problem, and F: \ A is no problem. However, because \ must be transferred during string expression, you must write it as F: \ \ a

2. The key of the whole program is the CopyFolder function in the filetest class, which is the function -# -! And note the introduction of Java. Java at the beginning of the program io.*; Due to the use of input and output streams

It may be difficult to understand the file part encountered by the cursor. In fact, it is like this. First, set the input stream of a file, specify the input from the file encountered by the cursor, and then specify the output to newpath / rename_ After the file name of the old file is the file directory, set a buffer array. For the file to be read by the file input stream, each time it calls the read method, it will continue to read the length of the buffer array at the last read position, store the read content in the buffer array, and overwrite all the contents before the buffer array, Then the file output stream will output all the contents of the buffer array to the specified location until the file input stream encounters - 1.

As for why the file input stream can be read in this order, it will continue to read the last read position every time, because when the file is to be read, the Java encapsulated FileInputStream The read method will also call the API of the operating system to read these data in turn. When reading file data, it must be sequential. It is impossible to read the first byte first and then the penultimate byte. When reading circularly, the read method will read the position + +, so each read will read the following bytes in sequence until the end mark of the file is encountered.

When the cursor encounters a folder, it can call itself again to complete the same operation, which is called iteration.

3. Therefore, the whole procedure is as follows:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>