Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android通用文件操作

android通用文件操作

編輯:關於Android編程

  最經用到android的SCCard的文件操作,因此稍作了整理,將它寫成一個簡單的工具類。其中,可以判斷SDCard的是否可用,可用存儲空間,文件的創建以及寫入數據。經過測試,可以正常使用。代碼如下:


[java]
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import android.os.Environment; 
import android.os.StatFs; 
import android.util.Log; 
 
public class FileUtil { 
    private static int bufferd = 1024; 
 
    private FileUtil() { 
    } 
 
    /*
     * <!-- 在SDCard中創建與刪除文件權限 --> <uses-permission
     * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--
     * 往SDCard寫入數據權限 --> <uses-permission
     * android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     */ 
 
    // =================get SDCard information===================  
    public static boolean isSdcardAvailable() { 
        String status = Environment.getExternalStorageState(); 
        if (status.equals(Environment.MEDIA_MOUNTED)) { 
            return true; 
        } 
        return false; 
    } 
 
    public static long getSDAllSizeKB() { 
        // get path of sdcard  
        File path = Environment.getExternalStorageDirectory(); 
        StatFs sf = new StatFs(path.getPath()); 
        // get single block size(Byte)  
        long blockSize = sf.getBlockSize(); 
        // 獲取所有數據塊數  
        long allBlocks = sf.getBlockCount(); 
        // 返回SD卡大小  
        return (allBlocks * blockSize) / 1024; // KB  
    } 
 
    /**
     * free size for normal application
     * 
     * @return
     */ 
    public static long getSDAvalibleSizeKB() { 
        File path = Environment.getExternalStorageDirectory(); 
        StatFs sf = new StatFs(path.getPath()); 
        long blockSize = sf.getBlockSize(); 
        long avaliableSize = sf.getAvailableBlocks(); 
        return (avaliableSize * blockSize) / 1024;// KB  
    } 
 
    // =====================File Operation==========================  
    public static boolean isFileExist(String director) { 
        File file = new File(Environment.getExternalStorageDirectory() 
                + File.separator + director); 
        return file.exists(); 
    } 
 
    /**
     * create multiple director
     * 
     * @param path
     * @return
     */ 
    public static boolean createFile(String director) { 
        if (isFileExist(director)) { 
            return true; 
        } else { 
            File file = new File(Environment.getExternalStorageDirectory() 
                    + File.separator + director); 
            if (!file.mkdirs()) { 
                return false; 
            } 
            return true; 
        } 
    } 
 
    public static File writeToSDCardFile(String directory, String fileName, 
            String content, boolean isAppend) { 
        return writeToSDCardFile(directory, fileName, content, "", isAppend); 
    } 
 
    /**
     * 
     * @param director
     *            (you don't need to begin with
     *            Environment.getExternalStorageDirectory()+File.separator)
     * @param fileName
     * @param content
     * @param encoding
     *            (UTF-8...)
     * @param isAppend
     *            : Context.MODE_APPEND
     * @return
     */ 
    public static File writeToSDCardFile(String directory, String fileName, 
            String content, String encoding, boolean isAppend) { 
        // mobile SD card path +path  
        File file = null; 
        OutputStream os = null; 
        try { 
            if (!createFile(directory)) { 
                return file; 
            } 
            file = new File(Environment.getExternalStorageDirectory() 
                    + File.separator + directory + File.separator + fileName); 
            os = new FileOutputStream(file, isAppend); 
            if (encoding.equals("")) { 
                os.write(content.getBytes()); 
            } else { 
                os.write(content.getBytes(encoding)); 
            } 
            os.flush(); 
        } catch (IOException e) { 
            Log.e("FileUtil", "writeToSDCardFile:" + e.getMessage()); 
        } finally { 
            try { 
                if(os != null){ 
                    os.close(); 
                } 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
        return file; 
    } 
 
    /**
     * write data from inputstream to SDCard
     */ 
    public File writeToSDCardFromInput(String directory, String fileName, 
            InputStream input) { 
        File file = null; 
        OutputStream os = null; 
        try { 
            if (createFile(directory)) { 
                return file; 
            } 
            file = new File(Environment.getExternalStorageDirectory() 
                    + File.separator + directory + fileName); 
            os = new FileOutputStream(file); 
            byte[] data = new byte[bufferd]; 
            int length = -1; 
            while ((length = input.read(data)) != -1) { 
                os.write(data, 0, length); 
            } 
            // clear cache  
            os.flush(); 
        } catch (Exception e) { 
            Log.e("FileUtil", "" + e.getMessage()); 
            e.printStackTrace(); 
        } finally { 
            try { 
                os.close(); 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
        } 
        return file; 
    } 
 
    /**
     * this url point to image(jpg)
     * 
     * @param url
     * @return image name
     */ 
    public static String getUrlLastString(String url) { 
        String[] str = url.split("/"); 
        int size = str.length; 
        return str[size - 1]; 
    } 
 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

public class FileUtil {
 private static int bufferd = 1024;

 private FileUtil() {
 }

 /*
  * <!-- 在SDCard中創建與刪除文件權限 --> <uses-permission
  * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--
  * 往SDCard寫入數據權限 --> <uses-permission
  * android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  */

 // =================get SDCard information===================
 public static boolean isSdcardAvailable() {
  String status = Environment.getExternalStorageState();
  if (status.equals(Environment.MEDIA_MOUNTED)) {
   return true;
  }
  return false;
 }

 public static long getSDAllSizeKB() {
  // get path of sdcard
  File path = Environment.getExternalStorageDirectory();
  StatFs sf = new StatFs(path.getPath());
  // get single block size(Byte)
  long blockSize = sf.getBlockSize();
  // 獲取所有數據塊數
  long allBlocks = sf.getBlockCount();
  // 返回SD卡大小
  return (allBlocks * blockSize) / 1024; // KB
 }

 /**
  * free size for normal application
  *
  * @return
  */
 public static long getSDAvalibleSizeKB() {
  File path = Environment.getExternalStorageDirectory();
  StatFs sf = new StatFs(path.getPath());
  long blockSize = sf.getBlockSize();
  long avaliableSize = sf.getAvailableBlocks();
  return (avaliableSize * blockSize) / 1024;// KB
 }

 // =====================File Operation==========================
 public static boolean isFileExist(String director) {
  File file = new File(Environment.getExternalStorageDirectory()
    + File.separator + director);
  return file.exists();
 }

 /**
  * create multiple director
  *
  * @param path
  * @return
  */
 public static boolean createFile(String director) {
  if (isFileExist(director)) {
   return true;
  } else {
   File file = new File(Environment.getExternalStorageDirectory()
     + File.separator + director);
   if (!file.mkdirs()) {
    return false;
   }
   return true;
  }
 }

 public static File writeToSDCardFile(String directory, String fileName,
   String content, boolean isAppend) {
  return writeToSDCardFile(directory, fileName, content, "", isAppend);
 }

 /**
  *
  * @param director
  *            (you don't need to begin with
  *            Environment.getExternalStorageDirectory()+File.separator)
  * @param fileName
  * @param content
  * @param encoding
  *            (UTF-8...)
  * @param isAppend
  *            : Context.MODE_APPEND
  * @return
  */
 public static File writeToSDCardFile(String directory, String fileName,
   String content, String encoding, boolean isAppend) {
  // mobile SD card path +path
  File file = null;
  OutputStream os = null;
  try {
   if (!createFile(directory)) {
    return file;
   }
   file = new File(Environment.getExternalStorageDirectory()
     + File.separator + directory + File.separator + fileName);
   os = new FileOutputStream(file, isAppend);
   if (encoding.equals("")) {
    os.write(content.getBytes());
   } else {
    os.write(content.getBytes(encoding));
   }
   os.flush();
  } catch (IOException e) {
   Log.e("FileUtil", "writeToSDCardFile:" + e.getMessage());
  } finally {
   try {
    if(os != null){
     os.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return file;
 }

 /**
  * write data from inputstream to SDCard
  */
 public File writeToSDCardFromInput(String directory, String fileName,
   InputStream input) {
  File file = null;
  OutputStream os = null;
  try {
   if (createFile(directory)) {
    return file;
   }
   file = new File(Environment.getExternalStorageDirectory()
     + File.separator + directory + fileName);
   os = new FileOutputStream(file);
   byte[] data = new byte[bufferd];
   int length = -1;
   while ((length = input.read(data)) != -1) {
    os.write(data, 0, length);
   }
   // clear cache
   os.flush();
  } catch (Exception e) {
   Log.e("FileUtil", "" + e.getMessage());
   e.printStackTrace();
  } finally {
   try {
    os.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return file;
 }

 /**
  * this url point to image(jpg)
  *
  * @param url
  * @return image name
  */
 public static String getUrlLastString(String url) {
  String[] str = url.split("/");
  int size = str.length;
  return str[size - 1];
 }

}

下面對代碼進行了測試,使用了AndroidJunitTest,當然另外還需要對SDCard查看操作的權限。

1、對android項目的mainfest.xml進行配置,需要注意targetPacket應當與包名保持一致。

 

 

[java]
//在mainfest標簽下  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> 
<instrumentation 
        android:name="android.test.InstrumentationTestRunner" 
        android:targetPackage="com.example.mygeneralutil" > 
</instrumentation> 
  
//在mainfest的application標簽下  
<uses-library android:name="android.test.runner"/> 

//在mainfest標簽下
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.example.mygeneralutil" >
</instrumentation>
 
//在mainfest的application標簽下
<uses-library android:name="android.test.runner"/>

 

2、簡單的測試代碼如下:


[java]
import android.test.AndroidTestCase; 
import android.util.Log; 
 
public class FileUtilTest extends AndroidTestCase { 
 
    public void testIsSdcardAvailable() { 
        FileUtil.isSdcardAvailable(); 
        Log.e("FileUtil", ""+FileUtil.isSdcardAvailable()); 
    } 
 
    public void testGetSDAllSizeKB() { 
        FileUtil.getSDAllSizeKB(); 
        Log.e("FileUtil", ""+(float)FileUtil.getSDAllSizeKB()/1024/1024); 
    } 
 
    public void testGetSDAvalibleSizeKB() { 
        FileUtil.getSDAvalibleSizeKB(); 
        Log.e("FileUtil", ""+(float)FileUtil.getSDAvalibleSizeKB()/1024/1024); 
    } 
 
    public void testIsFileExist() { 
        FileUtil.isFileExist("example"); 
        Log.e("FileUtil", ""+FileUtil.isFileExist("example")); 
    } 
 
    public void testCreateFile() { 
        Log.e("FileUtil", ""+FileUtil.createFile("forexample")); 
    } 
 
    public void testWriteToSDCardFileStringStringStringBoolean() { 
         
        fail("Not yet implemented"); 
    } 
 
    public void testWriteToSDCardFileStringStringStringStringBoolean() { 
        FileUtil.writeToSDCardFile("forexample", "123.txt",  
                "FileUtil.writeToSDCardFile", "utf-8", true); 
    } 
 
    public void testWriteToSDCardFromInput() { 
        fail("Not yet implemented"); 
    } 
 
    public void testGetUrlLastString() { 
        fail("Not yet implemented"); 
    } 
 

import android.test.AndroidTestCase;
import android.util.Log;

public class FileUtilTest extends AndroidTestCase {

 public void testIsSdcardAvailable() {
  FileUtil.isSdcardAvailable();
  Log.e("FileUtil", ""+FileUtil.isSdcardAvailable());
 }

 public void testGetSDAllSizeKB() {
  FileUtil.getSDAllSizeKB();
  Log.e("FileUtil", ""+(float)FileUtil.getSDAllSizeKB()/1024/1024);
 }

 public void testGetSDAvalibleSizeKB() {
  FileUtil.getSDAvalibleSizeKB();
  Log.e("FileUtil", ""+(float)FileUtil.getSDAvalibleSizeKB()/1024/1024);
 }

 public void testIsFileExist() {
  FileUtil.isFileExist("example");
  Log.e("FileUtil", ""+FileUtil.isFileExist("example"));
 }

 public void testCreateFile() {
  Log.e("FileUtil", ""+FileUtil.createFile("forexample"));
 }

 public void testWriteToSDCardFileStringStringStringBoolean() {
  
  fail("Not yet implemented");
 }

 public void testWriteToSDCardFileStringStringStringStringBoolean() {
  FileUtil.writeToSDCardFile("forexample", "123.txt",
    "FileUtil.writeToSDCardFile", "utf-8", true);
 }

 public void testWriteToSDCardFromInput() {
  fail("Not yet implemented");
 }

 public void testGetUrlLastString() {
  fail("Not yet implemented");
 }

}

 

 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved