• Android私有文件资源文件的存取


     

    一、私有文件夹下的文件存取(/data/data/包名)

     //写文件在./data/data/com.tt/files/下面
       public voidwriteFileData(String fileName,String message){ 
           try{ 
            FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
            byte [] bytes = message.getBytes(); 
            fout.write(bytes); 
             fout.close(); 
            } 
           catch(Exception e){ 
            e.printStackTrace(); 
           } 
       }
    //-------------------------------------------------------
    //读文件在./data/data/com.tt/files/下面
       public String readFileData(String fileName){ 
            String res=""; 
            try{ 
             FileInputStream fin = openFileInput(fileName); 
             int length = fin.available(); 
             byte [] buffer = new byte[length]; 
             fin.read(buffer);     
             res = EncodingUtils.getString(buffer, "UTF-8"); 
             fin.close();     
            } 
            catch(Exception e){ 
             e.printStackTrace(); 
            } 
            return res; 
        }  

     

    二、从resource中的raw文件夹中获取文件并读取数据(资源文件只能读不能写)

    public String getFromRaw(String fileName){  
        String res = "";  
           try{  
            InputStream in = getResources().openRawResource(R.raw.test1);   
            int length = in.available();        
            byte [] buffer = new byte[length];         
            in.read(buffer);          
            res = EncodingUtils.getString(buffer, "UTF-8");     
            in.close();             
           }  
           catch(Exception e){  
            e.printStackTrace();          
           }  
        return res ;  
       }  

    三、从asset中获取文件并读取数据(资源文件只能读不能写)

    public String getFromAsset(String fileName){  
        String res="";  
        try{  
         InputStream in = getResources().getAssets().open(fileName);    
         int length = in.available();          
            byte [] buffer = new byte[length];         
            in.read(buffer);             
            res = EncodingUtils.getString(buffer, "UTF-8");      
        }  
        catch(Exception e){  
         e.printStackTrace();          
        }  
        return res;  
       }

     

     

     

  • 相关阅读:
    【leetcode】反转字符串
    【leetcode】反转字符串 II
    053-669
    053-668
    053-667
    053-666
    053-665
    053-664
    053-663
    053-662
  • 原文地址:https://www.cnblogs.com/sishuiliuyun/p/2720911.html
Copyright © 2020-2023  润新知