需要在根SD卡中找到.txt文件的位置

时间:2014-04-07 17:04:57

标签: android gps

我试图在每次位置更改时将经度和纬度值写入文本文件。其结果应该是存储在SD卡上的文本文件,其中包含经度和纬度值的列表。应用程序成功获取经度和纬度,并弹出Toast通知,表示文件已成功保存。但是,我在SD卡的根目录中找不到该文本文件。

以下是代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity 
{
TextView textlat;
TextView textlong;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textlat = (TextView)findViewById(R.id.textlat);
    textlong = (TextView)findViewById(R.id.textlong);

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
            10000, 0, ll);
}

private class mylocationlistener implements LocationListener
{

    @Override
    public void onLocationChanged(Location location) 
    {
        if (location != null)
        {
            double pLong = location.getLongitude();
            double pLat = location.getLatitude();

            textlat.setText(Double.toString(pLat));
            textlong.setText(Double.toString(pLong));

            try 
            {
                File myFile = new File("/sdcard/mysdfile.txt");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter = 
                                        new OutputStreamWriter(fOut);
                myOutWriter.append(textlat.getText());

                myOutWriter.close();
                fOut.close();
                Toast.makeText(getBaseContext(),
                        "Done writing SD 'mysdfile.txt'",
                        Toast.LENGTH_SHORT).show();
            } 
            catch (Exception e) 
            {
                Toast.makeText(getBaseContext(), e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onProviderDisabled(String provider) 
    {

    }

    @Override
    public void onProviderEnabled(String provider) 
    {


    }

    @Override
    public void onStatusChanged(String provider, int status,
            Bundle extras) 
    {

    }       
}
}

基本上,具有位置值的文件在哪里?我觉得我错过了一些非常明显的东西......

1 个答案:

答案 0 :(得分:2)

您不应该尝试写入SD卡的根文件夹。由于安全问题,这将失败。试试这个:

File dir = Environment.getExternalStoragePublicDirectory();
File myFile = new File(dir, "mysdfile.txt");

然后,您可以在目录dir中找到该文件。如果您希望该文件专用于您的应用,请使用Context.getExternalFilesDir()代替Environment.getExternalStoragePublicDirectory()

另请参阅Storage Options

上的指南主题