我一直在试图创建一个名为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方法....现在的问题是,它不会写入我将它传递给文件的字符串。它确实创建了文件,但它是空的。 –