"Java" uses the file input and output stream to complete the operation of copying all files within a folder to another folder

Source: Internet
Author: User

I. BASIC OBJECTIVES

Use Java to do the following:

To copy all files within a folder to another folder, for example, A and B two folders in the F drive:


f:/a inside a bunch of files, run Java program will be copied all to F:/b, and complete the renaming, before all the files prefixed with rename_, if there is a folder, the folder is not renamed, the file is renamed, the same in all files before adding rename_ The prefix:



Second, the production process

1, first the main function is very simple, is called the above Filetest class in the CopyFolder function

public class FileCopy {public static void main (String args[]) {new Filetest (). CopyFolder ("f:/a", "f:/b");}}

It is worth noting that the path of passing past parameters, in Java, f:/a is no problem, f:\a is not a problem, but because \ in the string expression, must be transferred, so you have to write f:\\a

2, the key of the whole program in this Filetest class CopyFolder function, this class inside this function-_-! Also note the introduction of java.io.* at the beginning of the program;

Class Filetest {public void CopyFolder (string oldpath, String NewPath) {try {///If the folder does not exist, a new folder is created ("NewPath"). mkdir s ();//Read the contents of the entire folder into an array of file strings, set a cursor I below, and keep moving down to start reading the array file FileList = new file (OldPath);  string[] File = Filelist.list ();//To note that this temp is just a temporary file pointer//whole program and does not create temporary file temp = null;for (int i = 0; i < file.length; i++) {///if OldPath with the path delimiter/or \ End, then the oldpath/file name can be//otherwise you have to OldPath after the path delimiter and add the file name//Who knows you pass the parameter is f:/a or f:/a/ah?  if (Oldpath.endswith (file.separator)) {temp = new file (OldPath + file[i]);} else {temp = new file (OldPath + file.separator + File[i]);} If the cursor encounters a file if (Temp.isfile ()) {FileInputStream input = new FileInputStream (temp); FileOutputStream output = new FileOutputStream (newpath+ "/" + "rename_" + (Temp.getname ()). ToString ()); byte[] Bufferarray = new byte[1024 * 64];int prereadlength;while ((prereadlength = Input.read (bufferarray))! =-1) {Output.write ( Bufferarray, 0, prereadlength);} Output.flush (); Output.close (); Input.close ();} If the cursor encounters a folder if (Temp.isdirectory ()) {CopyfoldeR (OldPath + "/" + file[i], NewPath + "/" + File[i]);}}} catch (Exception e) {System.out.println ("error copying entire folder contents operation");}}}

It may be a bit difficult to understand the cursor encountered in the file section, in fact, the first set up a file input stream, specify from the cursor encountered in the file input, and then specify the output to the newpath/rename_ old file filename This file directory, after, set a buffer array, File input stream for the file that you want to read, each time the Read method is called, it will continue to read the contents of the buffer array Bufferarray in the last read position, storing the contents of the read to the buffer array, overwriting everything before the buffer array, The file output stream then outputs all the contents of the buffered array to the specified location until the file input stream encounters a-1.

As for why the file input stream can be sequentially, each time it continues to read the last read position, it is because when a file is read, the Java encapsulated Fileinputstream.read method also calls the operating system's API to read the data sequentially. It must be sequential to read the file data, it is impossible to say that the first byte is read first, and then the second-to-last byte is read. The Read method reads the position of + + at the time of the loop reading, thus causing each read to be sequentially read after the byte, until the end of the file is encountered.

When a cursor encounters a folder, it calls itself again to do the same, which is called an iteration.

3, therefore the entire procedure is as follows:

Import java.io.*;/** * * @param oldpath copied directory * @param newpath directory to be copied to * */class filetest {public void CopyFolder (String OldPath, String NewPath) {try {//If the folder does not exist, a new folder is established (A. NewPath). Mkdirs ();//Read the contents of the entire folder into an array of File strings, set a cursor I below, Move down and start reading this array file FileList = new file (OldPath);  string[] File = Filelist.list ();//To note that this temp is just a temporary file pointer//whole program and does not create temporary file temp = null;for (int i = 0; i < file.length; i++) {///if OldPath with the path delimiter/or \ End, then the oldpath/file name can be//otherwise you have to OldPath after the path delimiter and add the file name//Who knows you pass the parameter is f:/a or f:/a/ah?  if (Oldpath.endswith (file.separator)) {temp = new file (OldPath + file[i]);} else {temp = new file (OldPath + file.separator + File[i]);} If the cursor encounters a file if (Temp.isfile ()) {FileInputStream input = new FileInputStream (temp); FileOutputStream output = new FileOutputStream (newpath+ "/" + "rename_" + (Temp.getname ()). ToString ()); byte[] Bufferarray = new byte[1024 * 64];int prereadlength;while ((prereadlength = Input.read (bufferarray))! =-1) {Output.write ( Bufferarray, 0, prereadlength);} Output.flush (); Output.close (); Input.close ();} If the cursor encounters a folder if (Temp.isdirectory ()) {CopyFolder (OldPath + "/" + file[i], NewPath + "/" + File[i]);}}} catch (Exception e) {System.out.println ("error copying entire folder contents operation");}}} public class FileCopy {public static void main (String args[]) {new Filetest (). CopyFolder ("f:/a", "f:/b");}}


"Java" uses the file input and output stream to complete the operation of copying all files within a folder to another folder

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.