android 3d游戏研究(二)(边学边写,多谢高手指正,鞠躬) :txt文件读取

来源:互联网 发布:淘宝上办理流通许可证 编辑:程序博客网 时间:2024/04/28 08:02

1:sdcard

//该方法使用于小文件读取

 public String loadContentFromSDCard(String fileName){

        //从SD卡读取内容
        String content=null;        //sd卡 的内容字符串
        try{
            File f=new File("/sdcard/"+fileName);//待读取的文件
            int length=(int)f.length();
            byte[] buff=new byte[length];
            FileInputStream fis=new FileInputStream(f);
            fis.read(buff);    // 从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中
            fis.close();    //关闭此输入流并释放与此流关联的所有系统资源
            content=new String(buff,"UTF-8");
        }catch(Exception e){
            Toast.makeText(this, "对不起,没有找到文件",
                    Toast.LENGTH_SHORT).show();
        }
        return content;

    }


2:asset

public String loadFromAssert(String fileName){
        String content=null;//结果字符串
        try{
            InputStream is=this.getResources().getAssets().open(fileName);//打开文件
            int ch=0;
             ByteArrayOutputStream baos = new ByteArrayOutputStream();//实现了一个输出流
             while((ch=is.read())!=-1){
                   baos.write(ch);                    // 将指定的字节写入此 byte 数组输出流。                                    
             }
             byte[] buff=baos.toByteArray();    //以 byte 数组的形式返回此输出流的当前内容
             baos.close();                        //关闭流
             is.close();                        //关闭流
             content=new String(buff,"UTF-8");     //设置字符串编码
        }catch(Exception e){
            Toast.makeText(this, "对不起,没有找到指定文件!", Toast.LENGTH_SHORT).show();
        }
        return content;
    }