我有一个代码,可以根据用户选择的日期范围来打印.csv文件,但它会跳过最后一个数据,并且不会在.csv文件上打印。
下面是我的代码段,用于打印具有日期范围的.csv文件。
private fun saveCSV(){
var fileWriter: FileWriter? = null
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
fileWriter = FileWriter(File(Utility.getStorageDirectory, "hydrowatchData.csv"))
fileWriter.write("Station Name:, $stationName\n Station Address:, $stationAddress\n Station GPS:, $stationLat $stationLong\n\n")
fileWriter.write(CSV_HEADER+"\n")
for (data in dataList) {
if ("${data.date}" <= "${date_upto.text}"+"${time_upto.text}"+":00" && "${data.date}" >= "${date_from.text}"+"${time_from.text}"+":00") {
fileWriter.write("${data.date}" + ", " + "${data.water}" + ", " + "${data.rain}" + "\n")
if (data.water.toInt() < minWater){
minWater = data.water.toInt()
}
if (data.water.toInt() > maxWater){
maxWater = data.water.toInt()
}
if (data.rain.toInt() < minRain){
minRain = data.rain.toInt()
}
if (data.rain.toInt() > maxRain){
maxRain = data.rain.toInt()
}
}
}
fileWriter.write("\n\nWater_lvl\n")
fileWriter.write("Minimum value, $minWater\n")
fileWriter.write("Maximum value, $maxWater")
fileWriter.write("\n\nRain_lvl\n")
fileWriter.write("Minimum value, $minRain\n")
fileWriter.write("Maximum value, $maxRain")
Toast.makeText(this,"Write CSV successfully!", Toast.LENGTH_LONG).show()
val csvFile = File(Utility.getStorageDirectory, "hydrowatchData.csv")
showFileActions(csvFile.absolutePath, Utility.getStorageDirectory)
} else {
requestWriteStoragePermission()
}
} catch (e: Exception) {
Toast.makeText(this,"Writing CSV error!", Toast.LENGTH_LONG).show()
e.printStackTrace()
}
finally {
try {
fileWriter!!.close()
} catch (e: IOException) {
Toast.makeText(this, "Flushing/closing error!", Toast.LENGTH_LONG).show()
e.printStackTrace()
}
}
}