Android开发黄金代码

1.获取到当前屏幕的宽度和高度:

DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int widthScreen = metric.widthPixels;//屏幕宽度

int heightScreen= metric.heightPixels;//屏幕高度


2.获取SD卡的路径

private String getSDcard(){
File SDDir=null;
boolean isExist=Environment.getExternalStorageState().
equals(Environment.MEDIA_MOUNTED);
if(isExist){
SDDir = Environment.getExternalStorageDirectory();
}
return SDDir.toString();
}

输出路径为:/sdcard


3.读SD目录下文件内容

public String readSDFile(String fileName) { 

        StringBuffer sb = new StringBuffer(); 
        File file = new File(fileName); 
        try { 
            FileInputStream fis = new FileInputStream(file); 
            int c; 

          //fis.read()函数返回的值为但字节的数据,返回值为0--255之间的一个数据
            while ((c = fis.read()) != -1) { 
                sb.append((char) c); 
            } 
            fis.close(); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return sb.toString(); 
 } 


4.读内存文件内容

public static String readInternalFile(Context context, String fileName) {
try {
byte[] buffer = new byte[512];
int read = 0;
StringBuffer stringbuffer = new StringBuffer();
FileInputStream fis = context.openFileInput(fileName);
do {

//fis.read(buffer) 的返回值为buffer中最大的length长度,相当于fis.read(buffer,0,buffer.length)
read = fis.read(buffer);
if (read > 0)
        stringbuffer.append(new String(buffer, 0, read, "utf-8"));
} while (read != -1);
fis.close();
return stringbuffer.toString();
} catch (Exception e) {
return null;
}
}

5.获取当前Cpu的核数

private int getNumCores() {
// Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
// Check if filename is "cpu", followed by a single digit number
if (Pattern.matches("cpu[0-9]", pathname.getName())) {
return true;
}
return false;
}
}

try {
// Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
// Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
// Return the number of cores (virtual CPU devices)
return files.length;
} catch (Exception e) {
// Print exception
e.printStackTrace();
// Default to return 1 core
return 1;
}
}

6.读内存中的数据

   public static String readInternalFile(Context context, String fileName) {
try {
byte[] buffer = new byte[512];
int read = 0;
StringBuffer stringbuffer = new StringBuffer();
FileInputStream fis = context.openFileInput(fileName);
do {
read = fis.read(buffer);
if (read > 0)
stringbuffer.append(new String(buffer, 0, read, "utf-8"));
} while (read != -1);
fis.close();
return stringbuffer.toString();
} catch (Exception e) {
return null;
}
}


7. 写内存

// 将当前文件中的内容直接写入内存

 public void savetoMem(String fileName, String content) throws Exception {
// 私有
FileOutputStream fos = (FileOutputStream) this.openFileOutput(fileName,
Context.MODE_PRIVATE);

//fos.write(int oneByte):写一个单字节到相应的流中
fos.write(content.getBytes());

        fos.close();
}


8.读内存文件的另外一种写法方式:

private String readFromMem(String filename){
FileInputStream fis=null;
int len=0;
try {
fis = this.openFileInput(filename);
len = fis.available();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte convalue[] = new byte[len];
try {
fis.read(convalue);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

String tabValue="";
try {
tabValue = new String(convalue, "utf-8");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // tab.xml的值
return tabValue;
}


9.获取状态栏和标题栏

//获取状态栏的代码

private int getStatusBarHeight(){
        Rect frame = new Rect(); 
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        return statusBarHeight;
    }
    //获取标题栏的代码
    private int getTitleBarHeight(){
        int contentTop =
                getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
        int titleBarHeight = contentTop - getStatusBarHeight();
        return titleBarHeight;
    }

10

  1. /** 
  2.      * 获取文件夹大小 
  3.      * @param file File实例 
  4.      * @return long 单位为M 
  5.      * @throws Exception 
  6.      */  
  7.     public static long getFolderSize(java.io.File file)throws Exception{  
  8.         long size = 0;  
  9.         java.io.File[] fileList = file.listFiles();  
  10.         for (int i = 0; i < fileList.length; i++)  
  11.         {  
  12.             if (fileList[i].isDirectory())  
  13.             {  
  14.                 size = size + getFolderSize(fileList[i]);  
  15.             } else  
  16.             {  
  17.                 size = size + fileList[i].length();  
  18.             }  
  19.         }  
  20.         return size/1048576;  
  21.     }  

11 指定文件大小的设置

  1. /** 
  2.      * 文件大小单位转换 
  3.      *  
  4.      * @param size 
  5.      * @return 
  6.      */  
  7.     public static String setFileSize(long size) {  
  8.         DecimalFormat df = new DecimalFormat("###.##");  
  9.         float f = ((float) size / (float) (1024 * 1024));  
  10.   
  11.         if (f < 1.0) {  
  12.             float f2 = ((float) size / (float) (1024));  
  13.   
  14.             return df.format(new Float(f2).doubleValue()) + "KB";  
  15.   
  16.         } else {  
  17.             return df.format(new Float(f).doubleValue()) + "M";  
  18.         }  
  19.   
  20.     }  
12. 删除指定目录下的文件

  1. /** 
  2.      * 删除指定目录下文件及目录 
  3.      *  
  4.      * @param deleteThisPath 
  5.      * @param filepath 
  6.      * @return 
  7.      */  
  8.     public void deleteFolderFile(String filePath, boolean deleteThisPath)  
  9.             throws IOException {  
  10.         if (!TextUtils.isEmpty(filePath)) {  
  11.             File file = new File(filePath);  
  12.   
  13.             if (file.isDirectory()) {// 处理目录  
  14.                 File files[] = file.listFiles();  
  15.                 for (int i = 0; i < files.length; i++) {  
  16.                     deleteFolderFile(files[i].getAbsolutePath(), true);  
  17.                 }  
  18.             }  
  19.             if (deleteThisPath) {  
  20.                 if (!file.isDirectory()) {// 如果是文件,删除  
  21.                     file.delete();  
  22.                 } else {// 目录  
  23.                     if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除  
  24.                         file.delete();  
  25.                     }  
  26.                 }  
  27.             }  
  28.         }  
  29.     }  

13 .默认设置相应的设置

// get the current file size
public long getFileSizes(File f) throws Exception {
long s = 0;
if (f.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(f);
s = fis.available();

return s;
}


14.计算出当前文件和文件夹的大小

public static long getFileSize(File file)throws Exception{  
        long size = 0; 
        
        if(file.isDirectory()){
        File[] fileList = file.listFiles();  
            for (int i = 0; i < fileList.length; i++)  
            {  
                if (fileList[i].isDirectory())  
                {  
                    size = size + getFileSize(fileList[i]);  
                } else  
                {  
                    size = size + fileList[i].length();  
                }  
            }  
        }else if(file.isFile()){
        size =size+file.length();
        }
        
        return size;  
    }  

//calculate the file size
public String FormetFileSize(String fileName) {// 转换文件大小

LogUtil.d(TAG, "FormetFileSize,fileName:"+fileName);
File fileHTML = new File(fileName+".html");
File fileContent = new File(fileName+"_html");
long fileHTMLSize=0;
long fileContentSize=0;
try {
fileHTMLSize = getFileSize(fileHTML);
fileContentSize=getFileSize(fileContent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return calulateSize(fileHTMLSize+fileContentSize);
}


------------------------------------------------------------------------------------------------

  • •android:theme="@android:style/Theme.Dialog"   将一个Activity显示为对话框模式
  • •android:theme="@android:style/Theme.NoTitleBar"  不显示应用程序标题栏
  • •android:theme="@android:style/Theme.NoTitleBar.Fullscreen"  不显示应用程序标题栏,并全屏
  • •android:theme="@android:style/Theme.Light"  背景为白色
  • •android:theme="@android:style/Theme.Light.NoTitleBar"  白色背景并无标题栏
  • •android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen"  白色背景,无标题栏,全屏
  • •android:theme="@android:style/Theme.Black"  背景黑色
  • •android:theme="@android:style/Theme.Black.NoTitleBar"  黑色背景并无标题栏
  • •android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"    黑色背景,无标题栏,全屏
  • •android:theme="@android:style/Theme.Wallpaper"  用系统桌面为应用程序背景
  • •android:theme="@android:style/Theme.Wallpaper.NoTitleBar"  用系统桌面为应用程序背景,且无标题栏
  • •android:theme="@android:style/Theme.Wallpaper.NoTitleBar.Fullscreen"  用系统桌面为应用程序背景,无标题栏,全屏
  • •android:theme="@android:style/Translucent" 半透明效果
  • •android:theme="@android:style/Theme.Translucent.NoTitleBar"  半透明并无标题栏
  • •android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"  半透明效果,无标题栏,全屏
  • •android:theme="@android:style/Theme.Panel"
  • •android:theme="@android:style/Theme.Light.Panel
15 、 同时创建文件和目录,并且在相应的目录下写文件
方法一:
/**
   * 使用java同时创建文件和目录
   * @param filePath
   * @param listPath
   * @throws IOException
   */
  private static void wirteFile(String filePath) throws IOException{
   String writeContent="hello world";                            //待向文件中写字符
 
   File file = new File(filePath);                                      //创建当前的文件对象
   if(!file.exists()){                                                           //如果文件不存在                                                                         
    if(!file.getParentFile().exists()){                                //如果目录页不存在
     file.getParentFile().mkdirs();                                   //创建目录
    }
    file.createNewFile();                                                 //创建文件
   }
   
   FileWriter write = new FileWriter(file);
   write.write(writeContent);
   write.flush();
   write.close();
  }

16、 删除所有的文件目录和相应目录下的文件
/**
   * 删除所有的文件目录和相应目录下的文件
   * @param filePath
   * @return
   */
  private static boolean deleteFile(File file){
   if(file.isDirectory()){
    File[] children = file.listFiles();
    for (int i=0; i<children.length; i++) {
             boolean success = deleteFile(children[i]);
             if (!success) {
                  return false;
             }
       }
       }
    return file.delete();
  }
编写测试代码如下:

private static final String LIST_PATH="E:\\test";
 private static final String FILE_PATH=LIST_PATH+File.separator+"hello.txt";                                  
 
  public static void main(String[] args){
   
   try {
     wirteFile(FILE_PATH);
    read(FILE_PATH);
   } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
   }
   try {
           Thread.sleep(5000);
   } catch (InterruptedException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
   }
    deleteFile(new File(LIST_PATH));                      //在编写相应的函数时,可以根据相应的目录来传递相应的文件
  }


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值