2012-10-13 28 views
-1

我正在写一个将加速度计值写入文件的android应用程序,我得到的值显示在屏幕上,但我不知道是否将它们写入一个文件,如果它是我找不到该文件。将数据写入文件的应用程序

我有这种方法,但我不确定它是否正确;

public void WriteToFile() 
{ 
    try 
    { 
     final String accelValue = new String(accelXValue + "," + accelYValue + "," + accelZValue); 
     FileOutputStream fOut = openFileOutput("accelValue.txt", MODE_WORLD_READABLE); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut); 
     // Write the string to the file 
     osw.write(accelValue); 

     osw.flush(); 
     osw.close(); 
    } 
    finally 
    { 
     return; 
    } 
} 

这将文件存储在手机上?

我应该在我的代码中的某个地方调用它,还是可以遵循加速度计方法?

谢谢。

此外,应用程序需要创建它的写入文件。

https://stackoverflow.com/a/8738467/1383281

请问这个答案的帮助?

下面是新的代码,但它似乎还没有做任何事情。

public void WriteToFile() 
{ 
    File AccelData = new File(Environment.getExternalStorageDirectory() + File.separator + "AccelData.txt"); 
    try 
    { 
     if (!(AccelData.exists())) 
       { 
        AccelData.createNewFile(); 
       } 

     final String accelValue = new String(accelXValue + "," + accelYValue + "," + accelZValue); 
     FileOutputStream ADOut = openFileOutput("accelValue.txt", MODE_WORLD_READABLE); 
     OutputStreamWriter AD = new OutputStreamWriter(ADOut); 
     AD.write(accelValue); 
    } 
    finally 
    { 
     return; 
    } 
} 
+1

你或许应该打开文件一次,写所有你想要的值,然后将其关闭一次。该代码看起来像是打开文件并关闭它几次。 –

+0

我需要更改什么?我唯一能想到的就是删除'osw.close()'。我假设我也需要某种循环来保持它的值,并在应用程序关闭时关闭? – ELSheepO

回答

1
public void WriteToFile() 
{ 
    FileOutputStream fOut = openFileOutput("accelValue.txt", MODE_WORLD_READABLE); 
    OutputStreamWriter osw = new OutputStreamWriter(fOut); 

    try 
    { 
     final String accelValue = new String(accelXValue + "," + accelYValue + "," + accelZValue); 
     // Write the string to the file 
     osw.write(accelValue); 
    } 
    finally 
    { 
     osw.flush(); 
     osw.close(); 
     return; 
    } 
} 
相关问题