android studio 写文件,在Android Studio中从我自己的类读取和写入文本文件
我一直在試圖創建一個名為TextFileReaderWriter的類我想使用getters和setters來讀取和寫入文本文件,以便我可以調用類,并通過簡單地使用setfileContents(somestring)和somestring = getfileContents()像這樣 例如在程序的任何地方的方法:在Android Studio中從我自己的類讀取和寫入文本文件
TextFileReaderWriter trw = new TextFileReaderWriter();
trw.setfileContents(somestring); //this would write 'somestring' to the text file.
String somestring = trw.getfileContents(); //this would return 'somestring' from the text file.
這里就是我有這么遠,但它沒有寫入文件:
public class TextFileReaderWriter extends Activity{
String fileContents;
Context context;
String TAG = "MYTAG";
public TextFileReaderWriter(String fileContents, Context context) {
this.fileContents = fileContents;
this.context = context;
}
public String getFileContents() {
return fileContents;
}
public void setFileContents(String fileContents) {
this.fileContents = fileContents;
FileOutputStream fos = null;
try {
fos = context.openFileOutput("UserInputStore", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
try {
osw.write(fileContents);
Log.d(TAG, fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2015-04-13
CJG
+0
你的logcat的說?無論如何,首先你的getfilecontent沒有讀你的文件,它讀取你的變量filecontent,其次你寫在你的應用程序的私人文件夾 –
+0
你是故意試圖存儲它的內部存儲,還是你的意思是去外部?另外,你的'getFileContents()'實際上不會返回文件內容;當您重新啟動應用程序(或活動,甚至)時,數據將被gc'd。 –
+0
我還沒有編寫getFileContents到目前為止,我只使用setFileContents方法....現在的問題是,它不會寫入我將它傳遞給文件的字符串。它確實創建了文件,但它是空的。 –
總結
以上是生活随笔為你收集整理的android studio 写文件,在Android Studio中从我自己的类读取和写入文本文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android摄像头代码,Android
- 下一篇: android出现adpt2的问题,an