gpt4 book ai didi

java - 使用android存储文件和文件夹

转载 作者:行者123 更新时间:2023-12-01 12:27:03 25 4
gpt4 key购买 nike

我正在开发一个移动应用程序,我将在其中将生成的值保存到文件中。我已存储在文件中,文件也保存在文件夹中。但是从应用程序退出后,当我打开文件并尝试读取值时,它不读取文件。事实上,文件存储在设备内存中而不是外部设备中。我已在 list 文件中授予权限。

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

这里我附上我的代码。请指导我我犯了什么错误。//这里我存储两个数据

public void setData(String newData , String newTime , String fileName) throws JSONException {
try {
//FileOutputStream fou = openFileOutput("text.txt", MODE_WORLD_READABLE);
File sdcard = android.os.Environment.getExternalStorageDirectory();
File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
directory.mkdirs();
File file = new File(directory,fileName);
FileOutputStream fou = new FileOutputStream(file , true);
OutputStreamWriter osw = new OutputStreamWriter(fou);
try {
osw.write(String.valueOf(newData));
osw.append(',');
osw.write(String.valueOf(newTime));
osw.write(System.lineSeparator());
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//这里我正在读取移动设备中保存的文件内容

  @TargetApi(Build.VERSION_CODES.KITKAT)
@JavascriptInterface
public String ReadFile(String fileName)
{
String content;
ArrayList<String> arr = new ArrayList<String>();
//int linenumber = 0;
File sdcard = android.os.Environment.getExternalStorageDirectory();
File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
//File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
//File f = new File("");
Log.d(TAG, "acrd checking called");
System.out.println(sdcard.getAbsolutePath());
File file = new File(directory,fileName);
try (InputStream fis = new FileInputStream(file)) {
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
//char stringComma = new Character(',');
while ((content = br.readLine()) != null) {
// convert to char and display it
Log.d(TAG, "called");
arr.add(content);
Log.d(TAG, "called");
System.out.println(arr);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
return arr.toString();
}

可能出现什么问题?

最佳答案

完成写入后,您应该关闭输出流,例如fou.close()

关于java - 使用android存储文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26250938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com