我正在尝试在Xamarin Android中创建一个新的文本文件,并向该文件中写入一些字符串,但是却收到一条错误消息
ENOENT(无此文件或目录)
我的代码在下面详细解释
//Create a new file where we will write some texts or strings called "SaveMe.txt"
Java.IO.File root = new Java.IO.File(Android.OS.Environment.DirectoryDocuments, "SaveMe.txt");
//Check if file does not exist and create one
if(!root.Exists()){
root.Mkdir();
}
//Define the content of the source file that we desire to access
string content;
//Read some texts from an asset file located in the Assets folder called "source.txt"
try{
AssetManager assets=this.Assets;
//Define Steam reader that we will use to read the source file
using (StreamReader streamReadr = new StreamReader(assets.Open("source.txt"))){
content = streamReadr.ReadLine();
}
//Define new File writer class that we will use to edit the target file with
FileWriter writer = new FileWriter(root);
//Add string from source file to target file
writer.Append(content);
writer.Flush();
//Close file writer
writer.Close();
}catch(Java.IO.IOException m){
//Capture the exception for debugging
Toast.MakeText(this,m.Message,ToastLength.Long).Show();
}
当我签入应用程序的目录时,我看到“文档目录”,但是它是空的。任何能够成功创建该文本文件并写入该文件的建议都将受到赞赏
在浏览完我的代码和该论坛上的一些帖子之后,我发现您需要使用反斜杠来分隔字符串文件名,以便编译器知道如何结合目录和文本文件逻辑...。
//Access the root directory of Android Os
string abso = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
//Create New Folder in root called Tutorial
Java.IO.File newfile = new Java.IO.File(file1, filename);
//Check if folder exists and create one if false
if (!file1.Exists())
{
file1.Mkdir();
}
//Read from the stream and assign value to string variable
try
{
StreamReader streamReader = new StreamReader(assets.Open("source.txt"));
content = streamReader.ReadLine();
all = streamReader.ReadToEnd();
} catch (System.IO.IOException e)
{
Toast.MakeText(this, e.Message + " ", ToastLength.Long).Show();
}
//Define file name with folder delimiter character "/"
string filename = "/target.txt";
//Combine the dir and the file to create a java file
Java.IO.File newfile = new Java.IO.File(file1, filename);
//Check if file exists and create new one if false
if (!newfile.Exists())
{
try
{
newfile.CreateNewFile();
}catch(Java.IO.IOException k)
{
Toast.MakeText(this, k.Message + " ", ToastLength.Long).Show();
}
}
//Try to write to the file now
try
{
FileWriter fileWriter = new FileWriter(newfile);
fileWriter.Write(content);
fileWriter.Append(all);
fileWriter.Flush();
fileWriter.Close();
}
catch (System.IO.IOException j)
{
View view = this.FindViewById<RelativeLayout>(Resource.Id.listener);
Snackbar.Make(view, j.Message, Snackbar.LengthLong).Show();
}
它可以正常工作,何时可以在存储中成功找到文本文件
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句