我正在尝试创建文本文件并插入文本。 我在Manifest中添加了权限:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
string src = "ms-appx-web:///Assets/MyHTMLPage.html";
this.MyWebView.Navigate(new Uri(src));
}
}
但是当我尝试打开文件并插入测试时:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
我有这些错误:
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
}
File file = new File(Environment.getExternalStorageDirectory(), "myfile.txt");
try {
FileOutputStream stream = new FileOutputStream(file);
stream.write("test".getBytes());
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// FragmentTools.alertbox(getActivity(), "erreur d'écriture");;
}
答案 0 :(得分:0)
您在获得许可之前创建了文件,您应该在返回之后
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
return; // or prompt a message
}
答案 1 :(得分:0)
您正在
中提示用户if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
}
正确?因为您没有粘贴该代码...如果您不确定该怎么做,请查看来自Google的此示例:
https://github.com/googlesamples/android-PermissionRequest
它会对你有很大帮助。
另一个注意事项:如果您在API 23或更高版本上运行您的应用程序(它看起来像你),您必须在运行时请求权限。再次,请参阅谷歌示例,它显示了如何做到这一点。
答案 2 :(得分:0)
使用以下代码创建文本文件并将数据插入该文件。
它正在运行并经过测试
public void generateTxtOnSD(Context context) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, "YOUR FILE NAME");
FileWriter writer = new FileWriter(gpxfile);
writer.append("CONTENT TO INSERT");
writer.flush();
writer.close();
Toast.makeText(context, "Txt Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
在调用此函数之前,用户是否授予了检查权限。
为此,使用 PermissionAcceptor library
答案 3 :(得分:0)
最后它适用于此代码:
private void save(String string) {
Activity act = getActivity();
try {
FileOutputStream stream = act.openFileOutput("myfile.txt", Context.MODE_PRIVATE);
stream.write(string.getBytes());
stream.close();
} catch (FileNotFoundException e) {
FragmentTools.alertbox(getActivity(), "file not found");
} catch (IOException e) {
FragmentTools.alertbox(getActivity(), "can't write ");
}
}