• ANDROID对文件的操作


    1. import java.io.File;  
    2. import java.io.FileOutputStream;  
    3. import java.io.IOException;  
    4. import java.io.InputStream;  
    5. import java.io.OutputStream;  
    6. import android.os.Environment;  
    7. import android.os.StatFs;  
    8. import android.util.Log;  
    9.   
    10. public class FileUtil {  
    11.     private static int bufferd = 1024;  
    12.   
    13.     private FileUtil() {  
    14.     }  
    15.   
    16.     /* 
    17.      * <!-- 在SDCard中创建与删除文件权限 --> <uses-permission 
    18.      * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 
    19.      * 往SDCard写入数据权限 --> <uses-permission 
    20.      * android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
    21.      */  
    22.   
    23.     // =================get SDCard information===================  
    24.     public static boolean isSdcardAvailable() {  
    25.         String status = Environment.getExternalStorageState();  
    26.         if (status.equals(Environment.MEDIA_MOUNTED)) {  
    27.             return true;  
    28.         }  
    29.         return false;  
    30.     }  
    31.   
    32.     public static long getSDAllSizeKB() {  
    33.         // get path of sdcard  
    34.         File path = Environment.getExternalStorageDirectory();  
    35.         StatFs sf = new StatFs(path.getPath());  
    36.         // get single block size(Byte)  
    37.         long blockSize = sf.getBlockSize();  
    38.         // 获取所有数据块数  
    39.         long allBlocks = sf.getBlockCount();  
    40.         // 返回SD卡大小  
    41.         return (allBlocks * blockSize) / 1024; // KB  
    42.     }  
    43.   
    44.     /** 
    45.      * free size for normal application 
    46.      *  
    47.      * @return 
    48.      */  
    49.     public static long getSDAvalibleSizeKB() {  
    50.         File path = Environment.getExternalStorageDirectory();  
    51.         StatFs sf = new StatFs(path.getPath());  
    52.         long blockSize = sf.getBlockSize();  
    53.         long avaliableSize = sf.getAvailableBlocks();  
    54.         return (avaliableSize * blockSize) / 1024;// KB  
    55.     }  
    56.   
    57.     // =====================File Operation==========================  
    58.     public static boolean isFileExist(String director) {  
    59.         File file = new File(Environment.getExternalStorageDirectory()  
    60.                 + File.separator + director);  
    61.         return file.exists();  
    62.     }  
    63.   
    64.     /** 
    65.      * create multiple director 
    66.      *  
    67.      * @param path 
    68.      * @return 
    69.      */  
    70.     public static boolean createFile(String director) {  
    71.         if (isFileExist(director)) {  
    72.             return true;  
    73.         } else {  
    74.             File file = new File(Environment.getExternalStorageDirectory()  
    75.                     + File.separator + director);  
    76.             if (!file.mkdirs()) {  
    77.                 return false;  
    78.             }  
    79.             return true;  
    80.         }  
    81.     }  
    82.   
    83.     public static File writeToSDCardFile(String directory, String fileName,  
    84.             String content, boolean isAppend) {  
    85.         return writeToSDCardFile(directory, fileName, content, "", isAppend);  
    86.     }  
    87.   
    88.     /** 
    89.      *  
    90.      * @param director 
    91.      *            (you don't need to begin with 
    92.      *            Environment.getExternalStorageDirectory()+File.separator) 
    93.      * @param fileName 
    94.      * @param content 
    95.      * @param encoding 
    96.      *            (UTF-8...) 
    97.      * @param isAppend 
    98.      *            : Context.MODE_APPEND 
    99.      * @return 
    100.      */  
    101.     public static File writeToSDCardFile(String directory, String fileName,  
    102.             String content, String encoding, boolean isAppend) {  
    103.         // mobile SD card path +path  
    104.         File file = null;  
    105.         OutputStream os = null;  
    106.         try {  
    107.             if (!createFile(directory)) {  
    108.                 return file;  
    109.             }  
    110.             file = new File(Environment.getExternalStorageDirectory()  
    111.                     + File.separator + directory + File.separator + fileName);  
    112.             os = new FileOutputStream(file, isAppend);  
    113.             if (encoding.equals("")) {  
    114.                 os.write(content.getBytes());  
    115.             } else {  
    116.                 os.write(content.getBytes(encoding));  
    117.             }  
    118.             os.flush();  
    119.         } catch (IOException e) {  
    120.             Log.e("FileUtil", "writeToSDCardFile:" + e.getMessage());  
    121.         } finally {  
    122.             try {  
    123.                 if(os != null){  
    124.                     os.close();  
    125.                 }  
    126.             } catch (IOException e) {  
    127.                 e.printStackTrace();  
    128.             }  
    129.         }  
    130.         return file;  
    131.     }  
    132.   
    133.     /** 
    134.      * write data from inputstream to SDCard 
    135.      */  
    136.     public File writeToSDCardFromInput(String directory, String fileName,  
    137.             InputStream input) {  
    138.         File file = null;  
    139.         OutputStream os = null;  
    140.         try {  
    141.             if (createFile(directory)) {  
    142.                 return file;  
    143.             }  
    144.             file = new File(Environment.getExternalStorageDirectory()  
    145.                     + File.separator + directory + fileName);  
    146.             os = new FileOutputStream(file);  
    147.             byte[] data = new byte[bufferd];  
    148.             int length = -1;  
    149.             while ((length = input.read(data)) != -1) {  
    150.                 os.write(data, 0, length);  
    151.             }  
    152.             // clear cache  
    153.             os.flush();  
    154.         } catch (Exception e) {  
    155.             Log.e("FileUtil", "" + e.getMessage());  
    156.             e.printStackTrace();  
    157.         } finally {  
    158.             try {  
    159.                 os.close();  
    160.             } catch (Exception e) {  
    161.                 e.printStackTrace();  
    162.             }  
    163.         }  
    164.         return file;  
    165.     }  
    166.   
    167.     /** 
    168.      * this url point to image(jpg) 
    169.      *  
    170.      * @param url 
    171.      * @return image name 
    172.      */  
    173.     public static String getUrlLastString(String url) {  
    174.         String[] str = url.split("/");  
    175.         int size = str.length;  
    176.         return str[size - 1];  
    177.     }  
    178.   
    179. }  


    下面对代码进行了测试,使用了AndroidJunitTest,当然另外还需要对SDCard查看操作的权限。

    1、对android项目的mainfest.xml进行配置,需要注意targetPacket应当与包名保持一致。


    1. //在mainfest标签下  
    2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
    3. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />  
    4. <instrumentation  
    5.         android:name="android.test.InstrumentationTestRunner"  
    6.         android:targetPackage="com.example.mygeneralutil" >  
    7. </instrumentation>  
    8.    
    9. //在mainfest的application标签下  
    10. <uses-library android:name="android.test.runner"/>  


    2、简单的测试代码如下:

    1. import android.test.AndroidTestCase;  
    2. import android.util.Log;  
    3.   
    4. public class FileUtilTest extends AndroidTestCase {  
    5.   
    6.     public void testIsSdcardAvailable() {  
    7.         FileUtil.isSdcardAvailable();  
    8.         Log.e("FileUtil", ""+FileUtil.isSdcardAvailable());  
    9.     }  
    10.   
    11.     public void testGetSDAllSizeKB() {  
    12.         FileUtil.getSDAllSizeKB();  
    13.         Log.e("FileUtil", ""+(float)FileUtil.getSDAllSizeKB()/1024/1024);  
    14.     }  
    15.   
    16.     public void testGetSDAvalibleSizeKB() {  
    17.         FileUtil.getSDAvalibleSizeKB();  
    18.         Log.e("FileUtil", ""+(float)FileUtil.getSDAvalibleSizeKB()/1024/1024);  
    19.     }  
    20.   
    21.     public void testIsFileExist() {  
    22.         FileUtil.isFileExist("example");  
    23.         Log.e("FileUtil", ""+FileUtil.isFileExist("example"));  
    24.     }  
    25.   
    26.     public void testCreateFile() {  
    27.         Log.e("FileUtil", ""+FileUtil.createFile("forexample"));  
    28.     }  
    29.   
    30.     public void testWriteToSDCardFileStringStringStringBoolean() {  
    31.           
    32.         fail("Not yet implemented");  
    33.     }  
    34.   
    35.     public void testWriteToSDCardFileStringStringStringStringBoolean() {  
    36.         FileUtil.writeToSDCardFile("forexample", "123.txt",   
    37.                 "FileUtil.writeToSDCardFile", "utf-8", true);  
    38.     }  
    39.   
    40.     public void testWriteToSDCardFromInput() {  
    41.         fail("Not yet implemented");  
    42.     }  
    43.   
    44.     public void testGetUrlLastString() {  
    45.         fail("Not yet implemented");  
    46.     }  
    47.   
    48. }  
  • 相关阅读:
    Exploratory Undersampling for Class-Imbalance Learning
    Dynamic Programming
    Learning in Two-Player Matrix Games
    IELTS
    A Brief Review of Supervised Learning
    测试下载
    [.net基础]访问修饰符
    [随记][asp.net基础]Page_Load和OnLoad
    第一份工作经历
    JForum2.1.9 安装过程
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4389251.html
Copyright © 2020-2023  润新知