标题建议我在写文件和阅读文件时遇到问题。当我保存到内部存储时,我无法访问我的文件保存到的默认路径。我有2个哈希映射,其中一个包含要写入文件的当前数据,另一个是从文本文件读入时存储数据。我这样做是为了检查文件是否已正确写入。对不起,如果代码有任何初始错误,一旦我开始工作,它将被整理,我对使用Android和java相当新。
FILENAME
是一个String,它只包含文件名本身及其扩展名.txt
@Override
protected void onPause()
{
super.onPause();
File fp = new File(context.getFilesDir(), FILENAME);
if(fp.exists()){
Log.d("FILE", "EXISTS");
} else
Log.d("FILE", "DOES NOT EXISTS");
Log.d("HOME", "pause called");
// loop until entries are written to file
try{
if(!dataBank.isEmpty()){
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fos);
Iterator<Map.Entry<String, String>> i = dataBank.entrySet().iterator();
while(i.hasNext()){
String key = i.next().getKey();
Log.d("WRITE", key + "," + dataBank.get(key));
out.write(key + "," + dataBank.get(key) + "\n");
}
out.close();
fos.close();
}
FileInputStream fis = context.openFileInput(FILENAME);
BufferedReader bReader = new BufferedReader(new InputStreamReader(fis));
String read = "";
Log.d("FILE0", "READ");
while((read = bReader.readLine()) != null){
String[] dataArray = new String[2];
dataArray = read.split(",");
compare.put(dataArray[0], dataArray[1]);
}
bReader.close();
fis.close();
Log.d("FILE1", "READ");
}catch(Exception e){
Log.d("ERROR", "onPause!");
}
}
从Log.d
消息来看,这就是我得到的。我输入的订单是John
,Alice
,然后是Bob
。
我有一个EditText框,用户在其中键入一个名称和2个按钮,一个按钮可以让您从库中选择一个图像,然后从中获取文件路径并将其存储在与键相关的值中是在文本框中键入的名称。这些是在此方法中添加的:
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode == RESULT_OK){
old_User = username;
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
dataBank.put(old_User, selectedImagePath);
} else {
Toast.makeText(context, "FAILED TO GET FILEPATH...", duration).show();
}
}
谢谢!