2013-01-11 22 views
1

我正在做一個簡單的應用程序,用java加載和保存文件。我試圖將其移植到Android,並且無法使其看到該文件。在android中加載和保存數據文件

我目前正在使用的文件路徑是

private static final String SAVE_FILE_PATH = "data/save"; 

下面是從文件加載數據的功能:

public void loadData() throws FileNotFoundException { 
    File file = new File(SAVE_FILE_PATH); 

    Scanner scanner; 

    if (file.exists()) { 

     scanner = new Scanner(new FileInputStream(file)); 
     try { 
      while (scanner.hasNextLine()) { 
       allPlayers.add(new Player(scanner.nextLine())); 
      } 
     } finally { 
      scanner.close(); 
     } 
    } 
    else { 
     System.out.println("No file found"); 
    } 

     } finally { 
      scanner.close(); 
     } 
    } 

    } 
+0

你的文件路徑應該是以下格式..「到/ mnt/SD卡/ yourfilename」 – itsrajesh4uguys

+0

別t指望「/ mnt/sdcard」是正確的路徑。使用Environment.getExternalStorageDirectory() –

回答

2

雖然getExternalStorageDirectory()讓你的路徑,SD卡,可考慮使用Activity.getExternalFilesDir()這將返回(並在必​​要時創建)一個名義上私有的應用程序目錄。它的優點是,如果應用程序被卸載,它會自動刪除。這在API 8中是新的,因此如果您支持較舊的設備,則可能不希望使用它。

否則,您將不得不遵循K的建議。不要忘記創建您想要使用的存儲目錄。我的代碼通常是這樣的:

/** 
* Utility: Return the storage directory. Create it if necessary. 
*/ 
public static File dataDir() 
{ 
    File sdcard = Environment.getExternalStorageDirectory(); 
    if(sdcard == null || !sdcard.isDirectory()) { 
     // TODO: warning popup 
     Log.w(TAG, "Storage card not found " + sdcard); 
     return null; 
    } 
    File datadir = new File(sdcard, "MyApplication"); 
    if(!confirmDir(datadir)) { 
     // TODO: warning popup 
     Log.w(TAG, "Unable to create " + datadir); 
     return null; 
    } 
    return datadir; 
} 


/** 
* Create dir if necessary, return true on success 
*/ 
public static final boolean confirmDir(File dir) { 
    if(dir.isDirectory()) return true; 
    if(dir.exists()) return false; 
    return dir.mkdirs(); 
}  

現在用它來指定保存文件:

File file = new File(dataDir(), "save"); 

Scanner scanner; 

if (file.exists()) { 
    // etc. 
}