Onelong

分享知识,与你一起进步......
RSS icon Home icon
  • android IO的简单使用

    post by onelong / 2010-9-10 1:07 Friday [android]

    package com.hl;

    import java.io.FileInputStream;
    import java.io.FileOutputStream;

    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;

    public class FileIO extends Activity {
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            TextView txt = (TextView)findViewById(R.id.show);
            Button btn = (Button)findViewById(R.id.btn);
            btn.setOnClickListener(new OnClickListener() {
       
       @Override
       public void onClick(View v) {
        FileOutputStream fos = null;
              try {
         fos = openFileOutput("mytxt",Context.MODE_WORLD_WRITEABLE);
         fos.write("小明,你好!".getBytes("utf-8"));
        } catch (Exception e) {
         e.printStackTrace();
        }finally{
         try {
          if(fos != null){
           fos.flush();
           fos.close();
          }
         } catch (Exception e2) {
          e2.printStackTrace();
         }
        }
       }
      });
            FileInputStream fin = null;
           try {
            fin = openFileInput("mytxt");
            /*
             * 默认是防止/data/data/<package>/files
             * 可以把文件放在res/raw
             * xml文件可以放在res/xml下面
             * 或者sd卡中
             *
             * */
            byte[] reader = new byte[fin.available()];
            while(fin.read(reader) != -1);
            txt.setText(new String(reader));
      } catch (Exception e) {
       e.printStackTrace();
      }finally{
       try {
        if(fin != null){
         fin.close();
        }
       } catch (Exception e2) {
        e2.printStackTrace();
       }
      }
        }
    }

    引用地址:
     

    评论:

    1. VJai
      I've been looking for a post like this fevorer (and a day)

    我要评论