我的应用程序要求将文本保存(用户选择)到内部存储器中然后我想要一些喜欢的功能,用户点击按钮和喜欢的活动开始加载保存在内存中的文件(内部)。在我的程序中有多个文本,我使用随机生成器将文件保存为" fav1" " fav2"等等。整数部分是随机生成的。问题是,现在我不知道如何提供我的文件名,以便检索文件并在文本视图中显示。
public void load(String name){
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(filename)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
show.setText(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
所以你如何建议我检索文件,让任何人都感到沮丧。
答案 0 :(得分:1)
您可以通过以下代码轻松完成; 正如你所说,它从内部存储中读取文件。
private String readFromFile(String fname) {
String ret = "";
try {
InputStream inputStream = openFileInput(fname+".txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
show.setText(stringBuilder.toString());
inputStream.close();
}
}
修改强> 从路径中读取包含路径分隔符
File myFile = new File(fname+".txt"); // path contains full path to the file including file name
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = myReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
show.setText(stringBuilder.toString());
myReader.close();
编辑2
列出特定目录中的文件,并按名称选择所需文件。
File directory = new File(Environment.getExternalStorageDirectory()+"/sample");
// check the existance of the parent directory
if (directory.exists()) {
// get the list of files from the directory and keep it in an array of type File.
File[] fileList = directory.listFiles();
for (File file : fileList) {
//compares with filename: you can change this to your required file!
if (file.getName().equals("sam2.txt")) {
// method to read and show the text in text view
loadFile(file);
}
}
最后定义了loadFile()方法:
private void loadFile(File file) {
// TODO Auto-generated method stub
FileInputStream fIn;
try {
fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = myReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
show.setText(stringBuilder.toString());
myReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}