Java reads local disks and removable drive disks and copies files

Source: Internet
Author: User
Tags flush

1. Differentiate between local disks, removable disks, and drive disks

The code is as follows: Copy code

Package com. lvjava;
 
Import java. io. File;
 
Import javax. swing. filechooser. FileSystemView;
 
Public class FileSystemTest {
 
Private final static String localDiskName = "local disk ";
Private final static String removableDiskName = "removable disk ";
Private final static String enLocalDiskName = "Local Disk ";
Private final static String enRemovableDiskName = "Removable Disk ";
 
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
FileSystemView fileSystemView = FileSystemView. getFileSystemView ();
File [] roots = File. listRoots ();
For (File file: roots ){
String diskName = fileSystemView. getSystemTypeDescription (file );
System. out. println (diskName );
If (diskName. startsWith (localDiskName)
| DiskName. startsWith (enLocalDiskName) {// when the disk is a local disk or a removable disk
// Do something
} Else if (diskName. startsWith (removableDiskName)
| DiskName. startsWith (enRemovableDiskName )){
// Do something
            }
        }
    }
 
}

The output of the running code is as follows:
Local Disk
Local Disk
Local Disk
Local Disk
CD drive
CD drive
Removable disk

2. Copy a file using Java code

The code is as follows: Copy code

/**
* Moving a File to Another Directory
* @ Param srcFile eg: c: windowsabc.txt
* @ Param destPath eg: c: temp
* @ Return success
*/
Public static boolean move (String srcFile, String destPath ){
// File (or directory) to be moved
File file = new File (srcFile );
     
// Destination directory
File dir = new File (destPath );
     
// Move file to new directory and return result
Return file. renameTo (new File (dir, file. getName ()));
}

The following is a class for copying folders and files.

The code is as follows: Copy code

Package com. xuanwu. mtoserver. util;

Import java. io .*;

/**
* @ Author Toby: copy a folder or folder
*/
Public class FileUtil {

Public static void main (String args []) throws IOException {
// Source folder
String url1 = "D:/user/test /";
// Target folder
String url2 = "D:/user/testcopy /";
// Create the target folder
(New File (url2). mkdirs ();
// Obtain the current file or directory of the source folder
File [] file = (new File (url1). listFiles ();
For (int I = 0; I <file. length; I ++ ){
If (file [I]. isFile ()){
// Copy an object
String type = file [I]. getName (). substring (file [I]. getName (). lastIndexOf (".") + 1 );

If (type. equalsIgnoreCase ("txt") // transcoding
CopyFile (file [I], new File (url2 + file [I]. getName (), MTOServerConstants. CODE_UTF_8, MTOServerConstants. CODE_GBK );
Else
CopyFile (file [I], new File (url2 + file [I]. getName ()));
            }
If (file [I]. isDirectory ()){
// Copy the Directory
String sourceDir = url1 + File. separator + file [I]. getName ();
String targetDir = url2 + File. separator + file [I]. getName ();
CopyDirectiory (sourceDir, targetDir );
            }
        }
    }

// Copy an object
Public static void copyFile (File sourceFile, File targetFile) throws IOException {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
Try {
// Create a file input stream and buffer it
InBuff = new BufferedInputStream (new FileInputStream (sourceFile ));

// Create a file output stream and buffer it
OutBuff = new BufferedOutputStream (new FileOutputStream (targetFile ));

// Buffer array
Byte [] B = new byte [1, 1024*5];
Int len;
While (len = inBuff. read (B ))! =-1 ){
OutBuff. write (B, 0, len );
            }
// Refresh the buffer output stream
OutBuff. flush ();
} Finally {
// Close the stream
If (inBuff! = Null)
InBuff. close ();
If (outBuff! = Null)
OutBuff. close ();
        }
    }

// Copy a folder
Public static void copyDirectiory (String sourceDir, String targetDir) throws IOException {
// Create a target Directory
(New File (targetDir). mkdirs ();
// Obtain the current file or directory of the source folder
File [] file = (new File (sourceDir). listFiles ();
For (int I = 0; I <file. length; I ++ ){
If (file [I]. isFile ()){
// Source file
File sourceFile = file [I];
// Target file
File targetFile = new File (targetDir). getAbsolutePath () + File. separator + file [I]. getName ());
CopyFile (sourceFile, targetFile );
            }
If (file [I]. isDirectory ()){
// Prepare the copied source folder
String dir1 = sourceDir + "/" + file [I]. getName ();
// The target folder to be copied
String dir2 = targetDir + "/" + file [I]. getName ();
CopyDirectiory (dir1, dir2 );
            }
        }
    }

/**
     *
* @ Param srcFileName
* @ Param destFileName
* @ Param srcCoding
* @ Param destCoding
* @ Throws IOException
*/
Public static void copyFile (File srcFileName, File destFileName, String srcCoding, String destCoding) throws IOException {// Convert a File to a GBK File
BufferedReader br = null;
BufferedWriter bw = null;
Try {
Br = new BufferedReader (new InputStreamReader (new FileInputStream (srcFileName), srcCoding ));
Bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (destFileName), destCoding ));
Char [] cbuf = new char [2, 1024*5];
Int len = cbuf. length;
Int off = 0;
Int ret = 0;
While (ret = br. read (cbuf, off, len)> 0 ){
Off + = ret;
Len-= ret;
            }
Bw. write (cbuf, 0, off );
Bw. flush ();
} Finally {
If (br! = Null)
Br. close ();
If (bw! = Null)
Bw. close ();
        }
    }

/**
     *
* @ Param filepath
* @ Throws IOException
*/
Public static void del (String filepath) throws IOException {
File f = new File (filepath); // defines the File path
If (f. exists () & f. isDirectory () {// Determine whether the file is a directory or not.
If (f. listFiles (). length = 0) {// delete a file directly if no file exists in the directory
F. delete ();
} Else {// If yes, put the file into an array and determine whether there is a sub-directory
File delFile [] = f. listFiles ();
Int I = f. listFiles (). length;
For (int j = 0; j <I; j ++ ){
If (delFile [j]. isDirectory ()){
Del (delFile [j]. getAbsolutePath (); // recursively call the del method and obtain the subdirectory path
                    }
DelFile [j]. delete (); // delete an object
                }
            }
        }
    }
}

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.