关于Android编程中对于文件的读写的一些小程序

以下save()为我转载,忘记出处,如有侵权,联系我,我会即刻删除!
read(int)函数为我参照后的重写用来读取指定行的内容
readLines()函数用来读取文件的行数
 
//data中文件的读取与写入
private void save() {  //写入
        String content = editText.getText().toString()+"\n";  
        try {  
            /* 根据用户提供的文件名,以及文件的应用模式,打开一个输出流.文件不存系统会为你创建一个的, 
             * 至于为什么这个地方还有FileNotFoundException抛出,我也比较纳闷。在Context中是这样定义的 
             *   public abstract FileOutputStream openFileOutput(String name, int mode) 
             *   throws FileNotFoundException; 
             * openFileOutput(String name, int mode); 
             * 第一个参数,代表文件名称,注意这里的文件名称不能包括任何的/或者/这种分隔符,只能是文件名 
             *          该文件会被保存在/data/data/应用名称/files/chenzheng_java.txt 
             * 第二个参数,代表文件的操作模式 
             *          MODE_PRIVATE 私有(只能创建它的应用访问) 重复写入时会文件覆盖 
             *          MODE_APPEND  私有   重复写入时会在文件的末尾进行追加,而不是覆盖掉原来的文件 
             *          MODE_WORLD_READABLE 公用  可读 
             *          MODE_WORLD_WRITEABLE 公用 可读写 
             *  */  
            FileOutputStream outputStream = openFileOutput("b.txt",  
                    Activity.MODE_APPEND);  
            outputStream.write(content.getBytes());  
            outputStream.flush();  
            outputStream.close(); 
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
    }  
  
    /** 
     * @author chenzheng_java  此为原作者 但我做了较大的改动
     * 读取刚才用户保存的内容 
     */  
    private void read(int lineNumber) {
    int count = 1;
    String line;
    String content = "";   
        try {  
            FileInputStream inputStream = this.openFileInput("b.txt");
            InputStreamReader isr = new InputStreamReader(inputStream,"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            for(; count <= lineNumber && (line = br.readLine()) != null; count++)
            content = line.toString();    
            
            inputStream.close();  
            isr.close();
            br.close();
            text.setText(content);
  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();
        }  
    }
    
    private int readLines(){
    int i = 0;
    String line = "";
    try {
    FileInputStream inputStream = this.openFileInput("b.txt");
        InputStreamReader isr = new InputStreamReader(inputStream,"UTF-8");
        BufferedReader br = new BufferedReader(isr);
        while((line = br.readLine()) != null)
            i++; 
        inputStream.close(); 
        isr.close();
        br.close();
    } catch (FileNotFoundException e) {  
    e.printStackTrace();  
    } catch (IOException e) {  
    e.printStackTrace();
    }
    return i;
    }
posted @ 2014-03-05 14:34  云济术  阅读(473)  评论(0编辑  收藏  举报