File processing tool

Source: Internet
Author: User

File processing tool

File Processing:

Common Operations:

Obtain the absolute path and relative path of the file or folder. String path = File. getPath (); // relative path String path = File. getAbsoultePath (); // obtain the parent directory String parentPath = File of the File or folder from the absolute path. getParent (); get the Name of the File or folder String Name = File. getName (); create a File or folder File. mkDir (); // create a folder File. createNewFile (); // create a File to determine whether it is a File or a folder File. isDirectory () lists all the files in the folder and the folder name File [] files = File. listFiles (); Modify the folder and File name. renameTo (dest); delete a folder or File. delete ();

Added:

// Add //................................... ......... demarcation Line ...................................... ......... /*** determine whether the specified File exists * @ param filePath * @ return */public static boolean isFileExist (String filePath) {file File = new file (filePath); return File. exists ();}/*** create a file. If the file is successfully created, true * @ param filePath * @ return */public static boolean createFile (String filePath) is returned) {try {File file = new File (filePath ); If (! File. exists () {if (! File. getParentFile (). exists () {// create a folder file. getParentFile (). mkdirs ();} // create an empty file return file. createNewFile () ;}} catch (IOException e) {e. printStackTrace ();} return true ;} /*** write a specified file from an input stream * @ param FilePath: Path of the file to be created * @ param in * @ return */public static boolean writeFile (String FilePath, inputStream in) {try {// if the file is successfully created, continue; otherwise, false if (! CreateFile (FilePath) {return false;} FileOutputStream fos = new FileOutputStream (FilePath); int readCount = 0; int len = 1024; byte [] buffer = new byte [len]; while (readCount = in. read (buffer ))! =-1) {fos. write (buffer, 0, readCount);} fos. flush (); if (null! = Fos) {fos. close (); fos = null;} if (null! = In) {in. close (); in = null;} return true;} catch (IOException e) {e. printStackTrace ();} return false ;} /*** write bitmap to the file in the specified path * @ param bitmap Bitmap object * @ param destPath specified path * @ param quality compression rate, for example, when quality is set to 30, indicates compression of 70%; quality = 100 indicates not compression */public static void writeImage (Bitmap bitmap, String destPath, int quality) {try {FileAECS. deleteFile (destPath); if (FileAECS. createFile (destPath) {F IleOutputStream out = new FileOutputStream (destPath); if (bitmap. compress (Bitmap. compressFormat. JPEG, quality, out) {out. flush (); out. close (); out = null ;}} catch (IOException e) {e. printStackTrace ();}} /*** write data to a file ** @ param destFilePath path of the file to be created * @ param data file data to be written * @ param startPos start offset * @ param length the length of the written data * @ return returns true if the file is successfully written, false */public static boolean writeFi Le (String destFilePath, byte [] data, int startPos, int length) {try {if (! CreateFile (destFilePath) {return false;} FileOutputStream fos = new FileOutputStream (destFilePath); fos. write (data, startPos, length); fos. flush (); if (null! = Fos) {fos. close (); fos = null;} return true;} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return false ;}

Delete:

// Delete //................................... ......... demarcation Line ...................................... ......... /*** delete all files in the specified folder path, including the folder itself * @ param filePath folder path */public static void deleteAll (String filePath) {File file = new File (filePath); deleteFiles (file);}/*** delete all files in the specified folder, including the folder itself * @ param file File instance */public static void deleteFiles (File file) {if (file. isDirectory () {File [] listFiles = file. listFiles (); for (int I = 0; I <listFiles. length; I ++) {deleteFiles (listFiles [I]) ;}} file. delete ();} /*** delete a specified file or folder * @ param filePath Path of the file or folder to be deleted * @ return */public static boolean deleteFile (String filePath) {try {File file = new File (filePath); if (file. exists () {return file. delete () ;}} catch (Exception e) {e. printStackTrace ();} return false ;}

Modify:

// Modify //................................... ......... demarcation Line ...................................... ........ /*** modify all file suffixes in a specified folder in batches * @ param File * @ param oldSuffix * @ param newSuffix */public static void ReFileNameSuffix (file, String oldSuffix, String newSuffix) {if (file. isDirectory () {File [] listFiles = file. listFiles (); for (int I = 0; I <listFiles. length; I ++) {ReFileNameSuffix (listFiles [I], oldSuffix, newSuffix) ;}} else {file. renameTo (new File (file. getPath (). replace (oldSuffix, newSuffix )));}} /*** copy an object to another place * @ param sourceFile source file address * @ param destFile Destination Address * @ param shouldOverlay whether to overwrite * @ return */public static boolean copyFiles (string sourceFile, string destFile, boolean shouldOverlay) {try {if (shouldOverlay) {deleteFile (destFile);} FileInputStream fi = new FileInputStream (sourceFile); writeFile (destFile, fi); return true ;} catch (FileNotFoundException e) {e. printStackTrace ();} return false ;}

Read:

// Read //................................... ......... demarcation Line ...................................... ......... /*** read the specified file, returns the data in byte array form ** @ param filePath the path name of the file to be read * @ return byte array form data */public static byte [] readFile (String filePath) {try {if (isFileExist (filePath) {FileInputStream fi = new FileInputStream (filePath); return readInputStream (fi) ;}} catch (FileNotFoundException e) {e. printStackTr Ace ();} return null;}/*** reads data from a quantity stream and returns data in byte array form. * It is important to note that this method is generally used to read data from a local file, but it is often used for network operations (Network instability, available () method issues ). Therefore, this method should not be used for network streams. ** @ Param in the input stream to be read * @ return * @ throws java. io. IOException */public static byte [] readInputStream (InputStream in) {try {ByteArrayOutputStream OS = new ByteArrayOutputStream (); byte [] B = new byte [in. available ()]; int length = 0; while (length = in. read (B ))! =-1) {OS. write (B, 0, length);} B = OS. toByteArray (); in. close (); in = null; OS. close (); OS = null; return B;} catch (IOException e) {e. printStackTrace ();} return null;}/*** read network stream ** @ param in * @ return */public static byte [] readNetWorkInputStream (InputStream in) {ByteArrayOutputStream OS = null; try {OS = new ByteArrayOutputStream (); int readCount = 0; int len = 1024; byte [] buffer = New byte [len]; while (readCount = in. read (buffer ))! =-1) {OS. write (buffer, 0, readCount);} in. close (); in = null; return OS. toByteArray ();} catch (IOException e) {e. printStackTrace ();} finally {if (null! = OS) {try {OS. close ();} catch (IOException e) {e. printStackTrace ();} OS = null;} return null;}/*** read file data from resource raw, which can only be read, you cannot write * @ param Context * @ param test, for example, R. raw. test * @ param Charset encoding format, such as GBK, UTF-8, Unicode * @ return String */public static String getRawTest (Context, int test, String Charset) {String = null; try {// obtain the Raw data stream InputStream in = Context in the resource. getResources (). openRawResource (test); // get the data size int length = in. available (); // cache size byte [] buffer = new byte [length]; // read data in. read (buffer); // select the appropriate encoding type based on test.txt. If not adjusted, the String = EncodingUtils will be garbled. getString (buffer, Charset); // close in. close ();} catch (Exception e) {e. printStackTrace ();} return String;}/*** reads file data from the resource's asset and can only read, cannot Write * @ param Context * @ param fileName file name * @ param Charset encoding format, such as GBK, UTF-8, Unicode * @ return String */public static String getAssetTest (Context, string fileName, String Charset) {String = null; try {// obtain the asset data stream InputStream in = Context in the resource. getResources (). getAssets (). open (fileName); // get the data size int length = in. available (); // cache size byte [] buffer = new byte [length]; // read data in. read (buffer); // select the appropriate encoding type based on test.txt. If not adjusted, the String = EncodingUtils will be garbled. getString (buffer, Charset);} catch (Exception e) {e. printStackTrace ();} return String ;}

SD card processing:

// SD card related //.................................. .......... demarcation Line ......................................... /*** determine whether the SD card is mounted normally * @ return true normal mounting */public static boolean hasSDCard () {if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {return true;} else {return false;}/*** get the SD card root directory:/sdcard * @ return File */public static File getSDCardRoot () {if (hasSDCard () {return Environment. getExternalStorageDirectory ();} return null ;}

Obtain:

// Get //................................... ......... demarcation Line ......................................... /*** get the folder size * @ param file File instance * @ return long in the unit of M * @ throws Exception */public static long getFolderSize (File file) throws Exception {long size = 0; File [] fileList = file. listFiles (); for (int I = 0; I <fileList. length; I ++) {if (fileList [I]. isDirectory () {size = size + getFolderSize (fileList [I]);} else {size = size + fileList [I]. length () ;}} return size/(1024*1023 );} /*** obtain the relative path of a file or folder * @ param File * @ return String */public static String getFilePath (file) {String str = File. getPath (); return str;}/*** obtain the absolute path of a file or folder * @ param File * @ return String */public static String getFileAbsoultePath (file) {String str = file. getAbsolutePath (); return str ;}

 

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.