2012-10-13 29 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; 
    } 
} 
相關問題