2013-06-26 4 views
0
private void writeResults() { 
    // TODO Auto-generated method stub 
    String TAG = Screen3.class.getName(); 
    File file = new File(getFilesDir(), "history.txt"); 
    try { 
     file.createNewFile(); 
     FileWriter filewriter = new FileWriter(file, true); 
     BufferedWriter out = new BufferedWriter(filewriter); 
     out.write(workout + " - " + averageSpeed + " - " + totalDistance 
       + " - " + timerText + " - " + amountDonated + "\n "); 
     out.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     Log.e(TAG, e.toString()); 
    } 
} 

У меня есть этот код для записи статистики пользователя после тренировки в .txt-файл с именем history.txt, но при запуске это не дает ошибок. Но когда я просматриваю свой телефон до Android/data/packagename/, нет истории.txt, как получилось?Android File not writing

+1

Когда вы говорите «не дает никаких ошибок» - вы перехватываете все исключения и просто сбрасываете их на «System.out». Вы уверены, что сможете увидеть ошибки, которые * * произошли? –

+0

My LogCat на самом деле не дает мне никаких ошибок, могу ли я неправильно исключить исключение? – rockyl

+1

Ну, ты не * бросаешь * исключение вообще ... ты его поймаешь. Опять же, это записывается в System.out или, возможно, System.err - вы уверены, что этот вывод появляется в LogCat? Я предлагаю вам проверить это, преднамеренно бросая исключение и видя, отображается ли оно в ваших журналах. –

ответ

0

вы не вызывая внешний каталог хранения правильно

public class externalwriter{ 

private static File mFile = null; 


public static String getFileName() { 
    if (mFile.exists()) { 
     return mFile.getAbsolutePath(); 
    } else { 
     return ""; 
    } 
} 

/** 
* Creates the history file on the storage card. 
*/ 
private static void createFile() { 
    // Check if external storage is present. 
    if (android.os.Environment.getExternalStorageState().equals(
      android.os.Environment.MEDIA_MOUNTED)) { 

     // Create a folder History on storage card. 
final File path = new File(Environment.getExternalStorageDirectory() +   
         "/History"); 
     if (!path.exists()) { 
      path.mkdir(); 
     } 

     if (path.exists()) { 
      // create a file HISTORYFILE. 
      mFile = new File(path, "HISTORYFILE.txt"); 

      if (mFile.exists()) { 
       mFile.delete(); 
      } 

      try { 
       mFile.createNewFile(); 
      } catch (IOException e) { 
       mFile = null; 
      } 
     } 
    } 
} 

/** 
* Write data to the history file. 
* @param messages to be written to the history file. 
*/ 
public static void writeHistory(final String log) { 

    if ((mFile == null) || (!mFile.exists())) { 
     createFile(); 
    } 

    if (mFile != null && mFile.exists()) { 
     try { 

      final PrintWriter out = new PrintWriter(new BufferedWriter(
        new FileWriter(mFile, true))); 
      out.println(log); 
      out.close(); 

     } catch (IOException e) { 
      Log.w("ExternalStorage", "Error writing " + mFile, e); 
     } 
    } 
} 

/** 
* Deletes the history file. 
* @return true if file deleted, false otherwise. 
*/ 
public static boolean deleteFile() { 
    return mFile.delete(); 
} 
} 

этим путем записи данных в файл, который будет храниться на SDCard. скажите мне, если это поможет вам