你很接近。这是我做的事情,我检查是否有 SD 卡,如果没有,它将保存在本地(请记住,因为它是一个 Android 应用程序,所以您的所有数据都将保存在手机上),然后您创建如果没有目录,则写入文件。如果您有任何问题,请告诉我。这更多是为了写入,但读取同样简单,您只需创建一个缓冲读取器,给它文件,然后读取;就像您在代码中所做的一样。
我希望这有帮助:
SimpleDateFormat photoFormat = new SimpleDateFormat("ddMMyy-hhmmss");
// create formating for date
SimpleDateFormat sdf = new SimpleDateFormat("MMMddyy-hhmmss");
/*
* This sections checks the phone to see if there is a SD card. if
* there is an SD card, a directory is created on the SD card to
* store the test log results. If there is not a SD card, then the
* directory is created on the phones internal hard drive
*/
// if there is no SD card
if (Environment.getExternalStorageState() == null) {
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
/*
* Below is where the name of the test log is created.This can be
* changed for any other test methods
*/
String fileName = "TravelTestResults.csv";
/*
* Checks for existing test logs, and if they exist, they are
* deleted, creating a new test log for each testing method
*/
File logResults = new File(directory, fileName);
if (logResults.exists()) {
logResults.delete();
}
if (!logResults.exists()) {
logResults.createNewFile();
}
/*
* This creates the writing stream to log the test results This
* stream MUST be closed, using bw.close(), for the test results to
* show on the log. If the stream is not closed, when you open the
* text file that the results are stored in, the page will be blank.
*/
bw = new BufferedWriter(new FileWriter(logResults, true));
bw.write("Test Run, Test Result, Comments \"\n\"");
bw.close();