如何在 Google Glass 上保存和检索文件?

How to save and retrieve a file on Google Glass?

我需要能够将加速度计数据存储在 Google 眼镜上的文本文件中,将眼镜插入计算机,然后能够检索该写入的文件。

我没有收到任何 errors/exceptions--the 文件,只是从未出现过。

这是我目前所拥有的(不起作用):

public void onCreate(Bundle savedInstanceState) {
    ...
    try{
        accFile = openFileOutput("acc_data.csv",  MODE_APPEND | MODE_WORLD_READABLE);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
}

收集传感器数据绝对不是问题,因为我可以看到xyz,如果我设置断点。

public void onSensorChanged(SensorEvent event) {
    Sensor sensor = event.sensor;

    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
    String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    String outString = "\""+currentDateTimeString+"\","+x+","+y+","+z+"\n";

    if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        try {
            OutputStreamWriter osw = new OutputStreamWriter(accFile);
            osw.write(outString);
            osw.flush();
            osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void onDestroy() {
    ...
    if(accFile != null)
    {
        try {
            accFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

为了以防万一,android 清单有 android.permission.WRITE_EXTERNAL_STORAGE

openFileOutput 将 create/write 到应用程序内部的文件(参数 MODE_WORLD_READABLE 已被弃用)。理想情况下,这意味着您应该无法从计算机访问此文件。

改为使用外部存储 public 目录:

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File(path, filename);

要执行写入,请使用 FileOutputStream:

os = new FileOutputStream(file, true);
os.write(string.getBytes());

要从您的应用中执行读取,请使用 FileInputStream:

FileInputStream fis = new FileInputStream(file);
int c;
String temp = "";
while ( (c = fis.read()) != -1) {
     temp = temp + " | " + Character.toString((char) c);
}
Log.v(TAG, temp);

最后,要通过 adb shell 访问您的文件,只需访问 path.toString() 返回的目录即可。