安卓的FileInputStream阅读()txt文件为String [英] Android FileInputStream read() txt file to String
本文介绍了安卓的FileInputStream阅读()txt文件为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以帮助我任何专家?在我的Android的主要活动,我想一个字符串保存到一个文件,然后检索,如果用户面前。没能找到贴近我在做什么任何的例子。我想大多数AP preciate任何帮助!下面是我的测试情况下崩溃了:
字符串的TestString =作品;
字符串readString;
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
FileOutputStream中FOS;
尝试 {
FOS = openFileOutput(test.txt的,Context.MODE_PRIVATE);
fos.write(testString.getBytes());
fos.close();
}赶上(FileNotFoundException异常E){
e.printStackTrace();
}赶上(IOException异常E){
e.printStackTrace();
}
文件file = getBaseContext()getFileStreamPath(的test.txt)。
如果(file.exists()){
的FileInputStream FIS;
尝试 {
FIS = openFileInput(test.txt的);
fis.read(readString.getBytes());
fis.close();
}赶上(IOException异常E){
e.printStackTrace();
}
txtDate.setText(将String.valueOf(readString));
} 其他 {
//更多code
}
}
}
解决方案
有关读取文件试试这个:
的FileInputStream FIS;
FIS = openFileInput(test.txt的);
StringBuffer的fileContent =新的StringBuffer();
byte []的缓冲区=新的字节[1024];
而((N = fis.read(缓冲液))!= - 1)
{
fileContent.append(新字符串(缓冲液,0,n))的;
}
Any experts available to help me? In my Android main activity, I'm trying to save a String to a file and then retrieve it if the user has set it before. Wasn't able to find any examples close to what I am doing. I would most appreciate any help! Here is my test case that crashes:
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
}
}
}
解决方案
For reading file try this:
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));
}
这篇关于安卓的FileInputStream阅读()txt文件为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文