我是Android开发人员的新手,我想问这个。
我创建了一个将密码保存在txt文件中的Android程序。 我想检索这些密码并将它们显示在listView中。
以下是我为将密码保存到文件而编写的代码:
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_APPEND);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textView3.getText().toString()+"\n");
outputWriter.close();
//display password saved message
Toast.makeText(getBaseContext(), "Password saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
现在这是我的代码,它读取文件:
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textView4.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
我想知道是否有办法将这些密码显示在listView中。
即我正在寻找代码。我感谢任何帮助。
:注意:如果问题已经回答,我很抱歉。
解
感谢@ mehd-azizi我终于找到了解决问题的方法。
将读取的部分更改为:
public String[] readFileAsString(String fileName) {
Context context = this;
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
ArrayList<String> list=new ArrayList<String>();
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) {
list.add(line);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
String[] stockArr = new String[list.size()];
return list.toArray(stockArr);
}
并像这样使用它来读取文件并填充ListView:
ListView listView=(ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter=new ArrayAdapter<String(getApplicationContext(),android.R.layout.simple_list_item_1,readFileAsString("mytextfile.txt"));
listView.setAdapter(adapter);
答案 0 :(得分:0)
将读取的部分更改为:
public String[] readFileAsString(String fileName) {
Context context = this;
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
ArrayList<String> list=new ArrayList<String>();
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) {
list.add(line);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
String[] stockArr = new String[list.size()];
return list.toArray(stockArr);
}
并像这样使用它来读取文件并填写ListView
:
ListView listView=(ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,
readFileAsString("mytextfile.txt"));
listView.setAdapter(adapter);