安卓程序: 使用FileOutputStream写入SD卡的文件中

来源:互联网 发布:免费点赞软件 编辑:程序博客网 时间:2024/06/03 19:28

Android平台支持 java平台下的 文件I/O操作, 主要使用FileInputStream 和 FileOutputStream 这两个类来实现文件的存储与读取。获取这两个类对象的方式有两种。 
   一:第一种方式就是像Java平台下的实现方式一样通过构造器直接创建,如果需要向打开的文件末尾写入数据,可以通过使用构造器 FileOutputStream(File file, boolean append)将 append设置为true来实现。不过需要注意的是采用这种方式获得FileOutputStream 对象时如果文件不存在或不可写入时,会抛出 FileNotFoundException 异常。

   二:第二种获取 FileInputStream 和 FileOutputStream 对象的方式是调用 Context.openFileInput 和 Context.openFileOutput两个方法来创建。


////////////////////

浏览:安卓程序:读取手机时间和GPS数据,写入SD卡新建的gps.txt文件_张凯_新浪博客 http://t.cn/zOokhBv  

我仅仅在

FileOutputStream fos = new FileOutputStream(

            android.os.Environment.getExternalStorageDirectory()

            + "/gps.txt",true);

一句中增加了“,true" 红色部分, 那么上述程序就可以每隔500ms就写一次数据库。 太方便了。 


、、、、、、、、、、、、、、、、、、、、


 

package basic.android.lesson26;  

 

import java.util.Calendar;


import android.app.Activity;  

import android.content.Context;  

import android.content.Intent;  

import android.location.Criteria;  

import android.location.Location;  

import android.location.LocationListener;  

import android.location.LocationManager;  

import android.os.Bundle;  

import android.provider.Settings;  

import android.util.Log;  

import android.view.View;  

import android.widget.Button;  

import android.widget.TextView;  

import android.widget.Toast;  

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.provider.Settings.System;

import android.widget.ImageView;




  

public class TestMyGPS extends Activity {  

  

    private static final String TAG = "TestMyGPS";  

    Button mButton;  

    TextView tv1;  

    TextView mStatus;  

    TextView mTemp;  

    LocationManager mlm;  

    LocationListener locationListener;  

    String mFilter;  

    Calendar c = Calendar.getInstance();

   // public  String str1 = "《Android/OPhone开发完全讲义》";

   // String str1 = "《Android/OPhone开发完全讲义》";  在前面加不加Public,效果都一样

    //public static String str1 = "《Android/OPhone开发完全讲义》";

    public static String str1 = "《Android/OPhone开发完全讲义》";

      @Override  

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.main);  

  

        // 定义UI组件  

        mButton = (Button) findViewById(R.id.button1);  

        tv1 = (TextView) findViewById(R.id.textView1);  

        mStatus = (TextView) findViewById(R.id.show_status);  

        mTemp = (TextView) findViewById(R.id.temp_text);  

       

  

        mButton.setOnClickListener(new View.OnClickListener() {  

            public void onClick(android.view.View view) {  

                // 转至 GPS 设置界面  

                Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);  

                startActivityForResult(intent, 0);  

            }  

        });  

        // 获取LocationManager对象  

        mlm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);  

  

        // 定义Criteria对象  

  

        // 获取GPS信息提供者  

        Criteria filter = getFilter();  

        mFilter = mlm.getBestProvider(filter, true);  

  

//        try {  

//            mlm.setTestProviderEnabled(mFilter, true);  

//        } catch (IllegalArgumentException e) {  

//            String err = "IllegalArgumentException=" + e.getMessage();  

//            Log.e(TAG, err);  

//            Toast.makeText(this, err, Toast.LENGTH_LONG).show();  

//        }  

//        openGPS();  

        gpsStatus();  

        // 位置监听器  

        locationListener = new LocationListener() {  

  

            // 当位置改变时触发  

            public void onLocationChanged(Location location) {  

                updateLocation(location);  

                Toast.makeText(TestMyGPS.this, "onLocationChanged=" + location, Toast.LENGTH_LONG).show();  

                gpsStatus();  

                mTemp.setText("onLocationChanged="+location);  

            }  

  

            // Provider失效时触发  

            public void onProviderDisabled(String arg0) {  

                gpsStatus();  

                mTemp.setText("onProviderDisabled=" + arg0);  

            }  

  

            // Provider可用时触发  

            public void onProviderEnabled(String arg0) {  

                gpsStatus();  

                mTemp.setText("onProviderEnabled=" + arg0);  

            }  

  

            // Provider状态改变时触发  

            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {  

                mTemp.setText("onStatusChanged=" + arg0);  

            }  

        };  

  

        // 500毫秒更新一次,忽略位置变化  

        mlm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 3, locationListener);  

        //没有这一句,系统不会自动读星。 

   

      }

  

    private void openGPS() {  

//        if (mlm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  

//            Toast.makeText(this, " 位置源已设置! ", Toast.LENGTH_SHORT).show();  

//            return;  

//        }  

//  

//        Toast.makeText(this, " 位置源未设置! ", Toast.LENGTH_SHORT).show();  

    }  

  

    private Criteria getFilter() {  

        Criteria criteria = new Criteria();  

        // 设置定位精确度 Criteria.ACCURACY_COARSE 比较粗略, Criteria.ACCURACY_FINE则比较精细  

        criteria.setAccuracy(Criteria.ACCURACY_FINE);  

        // 设置是否需要海拔信息 Altitude  

        criteria.setAltitudeRequired(false);  

        // 设置是否需要方位信息 Bearing  

        criteria.setBearingRequired(false);  

        // 设置是否允许运营商收费  

        criteria.setCostAllowed(true);  

        // 设置对电源的需求  

        criteria.setPowerRequirement(Criteria.POWER_LOW);  

        return criteria;  

    }  

  

    private void gpsStatus() {  

        if (mlm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  

            mStatus.setText("GPS开启");  

        } else {  

            mStatus.setText("GPS未开启");  

            Toast.makeText(this, " 位置源未设置! ", Toast.LENGTH_SHORT).show();  

            // 转至 GPS 设置界面  

            Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);  

            startActivityForResult(intent, 0);  

        }  

    }  

  

    // 更新位置信息  

    private void updateLocation(Location location) {  

   

        if (location != null) {  

            tv1.setText("更新位置:" + location.toString() + "\n\t其中经度:" + location.getLongitude() + "\n\t其中纬度:"  

                    + location.getLatitude()); 

            try

            {

            FileOutputStream fos = new FileOutputStream(

            android.os.Environment.getExternalStorageDirectory()

            + "/gps.txt",true);

          //  InputStream is = getResources().getAssets().open("file.txt");


         //   byte[] buffer = new byte[8192];

         //   int count = 0;

         //   while ((count = is.read(buffer)) >= 0)

        //    {

         //   fos.write(buffer, 0, count);

          

         //   }

           // String str1 = "《Android/OPhone开发完全讲义》";这个语句放在这个地方,只能在这个函数内部使用,

            //但是放到主Activity里, 我们就可以在所有地方使用。 类似全局变量的使用。

            

            str1= Integer.toString(c.get(Calendar.YEAR))+"-"+Integer.toString(c.get(Calendar.MONTH)+1)+"-"+Integer.toString(c.get(Calendar.DAY_OF_MONTH))+" "+ Integer.toString(c.get(Calendar.HOUR_OF_DAY))+":"+Integer.toString(c.get(Calendar.MINUTE))+"  "+Double.toString(location.getLongitude())+","+Double.toString(location.getLatitude())+";";

            Toast.makeText(this,str1, Toast.LENGTH_LONG).show();

            

            fos.write(str1.getBytes("utf-8"));

                  fos.close();

           // is.close();

            Toast.makeText(this, "已成功地将经纬度数据将写到SD卡上的文件中.", Toast.LENGTH_LONG).show();

            }

            catch (Exception e)

            {

            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();

            }

        } else {  

            tv1.setText("更新位置失败");  

        }  

    }  

    public void onClick_SaveImageToSDCard(View view)

    {

    try

    {

    FileOutputStream fos = new FileOutputStream(

    android.os.Environment.getExternalStorageDirectory()

    + "/file.txt");

    InputStream is = getResources().getAssets().open("file.txt");


    byte[] buffer = new byte[8192];

    int count = 0;

    while ((count = is.read(buffer)) >= 0)

    {

    fos.write(buffer, 0, count);

  

    }

   // String str1 = "《Android/OPhone开发完全讲义》";这个语句放在这个地方,只能在这个函数内部使用,

    //但是放到主Activity里, 我们就可以在所有地方使用。 类似全局变量的使用。

    fos.write(str1.getBytes("utf-8"));

          fos.close();

    is.close();

    Toast.makeText(this, "已成功将文件写到SD卡上.", Toast.LENGTH_LONG).show();

    }

    catch (Exception e)

    {

    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();

    }

    }


    public void onClick_ReadImageFromSDCard(View view)

    {

    String filename = android.os.Environment.getExternalStorageDirectory()

    + "/gps.txt";

    if (!new File(filename).exists())

    {

    Toast.makeText(this, "还没有往SD卡写入文件", Toast.LENGTH_LONG).show();

    return;

    }

    //ImageView imageView = (ImageView) findViewById(R.id.imageview);

    TextView textView = (TextView)findViewById(R.id.textview);

    try

    {

    FileInputStream fis = new FileInputStream(filename);

    //Bitmap bitmap = BitmapFactory.decodeStream(fis);

    //imageView.setImageBitmap(bitmap);


    //fis.close();

    //?InputStream is = openFileInput("file.txt");

    byte[] buffer = new byte[8192];

    int byteCount = fis.read(buffer);

    String str2 = new String(buffer, 0, byteCount, "utf-8");

    //TextView textView = (TextView)findViewById(R.id.textview);

    textView.setText(str2);

    fis.close();

    }

    catch (Exception e)

    {

    // TODO: handle exception

    }

    }

       @Override  

    protected void onDestroy() {  

        mlm.removeUpdates(locationListener);  

//        mlm.setTestProviderEnabled(mFilter, false);  

        super.onDestroy();  

    }  

}  


原创粉丝点击