2012-02-01 39 views
28

任何專家可以幫助我?在我的Android主要活動中,我試圖將一個字符串保存到一個文件中,然後在用戶之前設置它時檢索它。無法找到任何接近我所做事情的例子。我將非常感謝任何幫助!下面是我崩潰的測試案例:Android FileInputStream讀取()txt文件到字符串

String testString = "WORKS"; 
String readString; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    FileOutputStream fos; 

    try { 
     fos = openFileOutput("test.txt", Context.MODE_PRIVATE); 
     fos.write(testString.getBytes()); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 

    } catch (IOException e) { 
     e.printStackTrace(); 

    } 

    File file = getBaseContext().getFileStreamPath("test.txt"); 

    if (file.exists()) { 

     FileInputStream fis; 

     try { 
      fis = openFileInput("test.txt"); 
      fis.read(readString.getBytes()); 
      fis.close(); 

     } catch (IOException e) { 
      e.printStackTrace(); 

     } 

     txtDate.setText(String.valueOf(readString)); 

     } else { 
        // more code 
     } 
    } 
} 
+0

爲什麼使用文件?嘗試使用[SharedPreferences](http://developer.android.com/reference/android/content/SharedPreferences.html) - 少得多的代碼和混亂。 – Jens 2012-02-01 12:16:29

+0

你有什麼錯誤? – 2012-02-01 12:19:39

回答

59

對於閱讀文件試試這個:

FileInputStream fis; 
fis = openFileInput("test.txt"); 
StringBuffer fileContent = new StringBuffer(""); 

byte[] buffer = new byte[1024]; 

while ((n = fis.read(buffer)) != -1) 
{ 
    fileContent.append(new String(buffer, 0, n)); 
} 
+2

請幫我一下,第二行顯示錯誤openFileInput未定義...該怎麼辦? – 2012-09-19 04:53:13

+0

@someone_smiley - 你在哪寫這行代碼?活動的方法。因此,要麼將您的代碼放在活動中,要麼使用此方法的活動上下文.. – user370305 2012-09-19 05:11:57

+0

hi @ user370305 - 我的代碼不在任何活動中。它只是我打算設計的一個類來緩解一些任務。我會將文件路徑作爲參數從一個類(再次不是活動)發送給它,讓方法完成剩下的工作。請諮詢我如何才能做到這一點。感謝您的時間 – 2012-09-19 08:42:33

35

嘗試是這樣的

public void writeData (String data) { 
     try { 
      FileOutputStream fOut = openFileOutput ("settings.dat" , MODE_WORLD_READABLE) ; 
      OutputStreamWriter osw = new OutputStreamWriter (fOut) ; 
      osw.write (data) ; 
      osw.flush () ; 
      osw.close () ; 
     } catch (Exception e) { 
      e.printStackTrace () ; 
     } 
    } 

    public String readSavedData () { 
     StringBuffer datax = new StringBuffer(""); 
     try { 
      FileInputStream fIn = openFileInput ("settings.dat") ; 
      InputStreamReader isr = new InputStreamReader (fIn) ; 
      BufferedReader buffreader = new BufferedReader (isr) ; 

      String readString = buffreader.readLine () ; 
      while (readString != null) { 
       datax.append(readString); 
       readString = buffreader.readLine () ; 
      } 

      isr.close () ; 
     } catch (IOException ioe) { 
      ioe.printStackTrace () ; 
     } 
     return datax.toString() ; 
    } 
+0

我認爲這是一個更好的解決方案,然後其他答案。如果在那裏有一個非常大的文件,並且你不能將整個文件讀到內存中,那麼你可以改變時間來一行一行地處理它。另一種解決方案並不像這個那樣容易改變。 – rml 2013-06-21 22:00:55

+0

用StringBuilder替換'datax = datax + readString;' – marcinj 2014-01-18 14:30:18

+0

難道是有'datax.append(System.lineSeparator());'丟失? 'StringBuilder'比'StringBuffer'更高效 - 除此之外:謝謝,非常有幫助。 – Martin 2015-01-11 18:49:57

1

少即是多;

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     TextView tvText = (TextView) findViewById(R.id.tvText); 

     try { 
      // Create File and Content 
      String FILE_NAME = "hallo.txt"; 
      String content = "Hallo Welt!"; 

      FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE); 
      fos.write(content.getBytes()); 
      fos.close(); 

      // Read File and Content 
      FileInputStream fin = openFileInput(FILE_NAME); 
      int size; 
      String neuText = null; 

      // read inside if it is not null (-1 means empty) 
      while ((size = fin.read()) != -1) { 
       // add & append content 
       neuText += Character.toString((char) size); 
      } 
      // Set text to TextView 
      tvText.setText(neuText); 

     } catch (Exception error) { 
      // Exception 
     } 
    } 
}