2012-12-26 87 views
3

我有一個需要(可能是一瞥)經驗豐富的Java專業人員的應用程序。引擎完美工作,但我無法將數據保存到文本文件;此外,我必須連接我的平板電腦,卸載舊的應用程序,複製apk,並在每次調試文件操作時重新安裝,因爲我無法在模擬器中寫入磁盤。用Java編寫文本文件

我說:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

到應用程序標籤的清單之外還有試過無數寫入到文件的方法。例外情況是(取決於當前的嘗試)eacces或文件不存在。我也一整天都在Google上查找解決方案。有人有任何想法嗎?

// this is a canned method that should presumably work 
private void writeStringToTextFile(String s, String f){ 
File sdCard = Environment.getExternalStorageDirectory(); 
File dir = new File (sdCard.getAbsolutePath()); 
dir.mkdirs(); 
File file = new File(dir, f); 
try{ 
    FileOutputStream f1 = new FileOutputStream(file,false); //True = Append to file, false = Overwrite 
    PrintStream p = new PrintStream(f1); 
    p.print(s); 
    p.close(); 
    f1.close(); 
} catch (FileNotFoundException e) { 
} catch (IOException e) { 
} } 


// this is the save method 
// it has been modified a little less than a million times today 
// some lines may be unnecessary because I have tried several approaches 
    public void saveSystem(View view){ 
      String s=""; 
      String FILENAME = "data/data/TopExpertAndroid/" + fileName; 
      FileOutputStream f; 
      File file = new File(FILENAME); 
      if(!(file.exists())){ 
      try{ 
       file.createNewFile();} 
      catch(Exception e){ 
       showSplash(e.getMessage() + e.getCause(), "OK"); 
       return;}} 
      try{ 
       getFile(); 
       if(fileName.equals("")){} 
       else{ 
        f = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
        for(int temp=0; temp<50; temp++){ 
         for(int loop=0; loop<50; loop++){ 
          s += topExpert.nodeBank[temp][loop].activationResponse + "\n"; 
          s += topExpert.nodeBank[temp][loop].display + "\n"; 
          s += topExpert.nodeBank[temp][loop].falseLink + "\n"; 
          s += topExpert.nodeBank[temp][loop].identifier + "\n"; 
          if(topExpert.nodeBank[temp][loop].isTop){ 
           s += "true";} 
          else{ 
           s += "false";} 
          s += "\n" + topExpert.nodeBank[temp][loop].trueLink + "\n";}} 
          writeStringToTextFile(s,FILENAME); 
       }} 
      catch(Exception e){ 
       showSplash(e.getMessage() + e.getCause(), "OK");}} 
+1

上帝,我是如何愛那些空的'catch'塊。用'e.printStackTrace()'(兩個!)填充它們並將StackTrace添加到您的問題中。 –

回答

4

FILENAME變量可能缺少/開頭:

String FILENAME = "/data/data/TopExpertAndroid/" + fileName; 

而且你應該使用getDataDirectorygetExternalStorageDirectory,而不是...

但你說的不能夠什麼寫入模擬器的磁盤似乎很奇怪...?

+0

......我簡直不敢相信。是的,就是這樣(路徑試圖在寫入方法中加載爲文件)。我該如何回答這個問題,並在何處提供信用證? –

+0

很高興它可以幫助...有時它是這樣的小事情,這使得你拉你的頭髮...... :)答案的左側應該有一個複選標記以接受它。 – Matthieu