我想阅读一个使用OutputStreamWriter在另一个活动中编写的文本文件。 这是我在Sale.java中的readFromFile方法:
private int readFromFile(String request) {
int res = 0;
try {
//InputStream inputStream = openFileInput("dalassnums.txt");
File file=new File("dalassnums.txt");
InputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
String s=bufferedReader.readLine();
if(receiveString==request) {
res=Integer.valueOf(s);
break;
}
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
res=0;
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return res;
}
这是MainActivity.java中的writeToFile方法:
private void writeToFile2(String numchar) {
try {
//File file=new File("dalassnums.txt");
//OutputStream outputStream=new FileOutputStream(file);
OutputStreamWriter outputStreamWriter;
if(numchar=="1") outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_PRIVATE));
else outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_APPEND));
for(int k=0; k<imageNums.size();k+=2){
outputStreamWriter.append(imageNums.get(k));
outputStreamWriter.append("\n");
outputStreamWriter.append(imageNums.get(k+1));
outputStreamWriter.append("\n");
}
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
执行readFromFile时,返回0表示找不到文件; 我读过关于传递上下文但我不知道要传递什么上下文;并且想知道除了传递上下文之外是否还有其他方式。 任何帮助将不胜感激。
答案 0 :(得分:2)
使用openFileInput
中的readFromFile
,例如:
openFileInput() and/or openFileOutput() i/o streams silently failing
另一个问题是这是无效的:
if(numchar=="1")
你应该
if(numchar.equals("1"))
否则你比较参考值而不是字符串
的内容