我正在尝试用Xamarin Android写一个文件。 这是我的代码:
try
{
string r = (string)(DateFormat.Format("yyyy-MM-dd-hh-mm-ss", new Date()));
string logFileBaseName = "drLog." + r; pause();
mAccelLogFileWriter = new FileWriter(new File(STORAGE_DIR, logFileBaseName + ".accel.csv"));
mStepLogFileWriter = new FileWriter(new File(STORAGE_DIR, logFileBaseName + ".steps.csv"));
}
catch (IOException e)
{
Log.Error(TAG, "Creating and opening log files failed!", e);
e.PrintStackTrace();
throw new RuntimeException(e);
}
知道我定义了:
protected string STORAGE_DIR = SAMPLES_DIR + File.Separator + "dr";
protected static readonly string SAMPLES_DIR = Android.OS.Environment.ExternalStorageDirectory + File.Separator + "samples_exp";
问题是我在创建文件mAccelLogFileWriter时遇到此异常。 这个例外说:
Java.Lang.RuntimeException: java.io.FileNotFoundException: /storage/emulated/0/samples_exp/dr/drLog.2016-07-21-09-22-59.accel.csv: open failed: ENOENT (No such file or directory)
当我调试代码时,我发现例如:SAMPLES_DIR =“/ storage / emulated / 0 / samples_exp” 我正在尝试获取外部存储目录(SD卡)。
你能告诉我我的代码有什么问题吗?
答案 0 :(得分:2)
在创建Java.IO.File.Mkdirs
之前,使用Java.IO.FileWriter
制作路径中的所有目录。
string SAMPLES_DIR = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "samples_exp");
string STORAGE_DIR = Path.Combine(SAMPLES_DIR, "dr");
var r = DateFormat.Format("yyyy-MM-dd-hh-mm-ss", new Java.Util.Date());
var logFileBaseName = "drLog." + r;
// ~~~~
var storageDirs = new Java.IO.File(STORAGE_DIR);
storageDirs.Mkdirs();
// ~~~~
var mAccelLogFileWriter = new Java.IO.FileWriter(new Java.IO.File(STORAGE_DIR, logFileBaseName + ".accel.csv"));
var mStepLogFileWriter = new Java.IO.FileWriter(new Java.IO.File(STORAGE_DIR, logFileBaseName + ".steps.csv"));
adb shell ls -R sdcard/samples_exp
sdcard/samples_exp:
dr
sdcard/samples_exp/dr:
drLog.2016-07-21-03-50-52.accel.csv
drLog.2016-07-21-03-50-52.steps.csv