我的android应用创建了一个csv文件,并立即将其共享为以下代码。该应用程序正常启动,但是当我选择任何应用程序进行共享时,没有附加文件。请帮助解决此问题。
class MainActivity : AppCompatActivity() {
private val CSV_HEADER = "id,name,address,age"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val qponFile = File.createTempFile("qpon", "csv")
var fileWriter: FileWriter? = null
try {
fileWriter = FileWriter("qpon.csv")
fileWriter.append(CSV_HEADER)
fileWriter.append('\n')
fileWriter.append("aaaaa")
fileWriter.append(',')
fileWriter.append("bbbbb")
fileWriter.append(',')
fileWriter.append("cccccc")
fileWriter.append(',')
fileWriter.append("dddddd")
fileWriter.append('\n')
println("Write CSV successfully!")
} catch (e: Exception) {
println("Writing CSV error!")
e.printStackTrace()
}
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(Intent.EXTRA_STREAM, qponFile)
sendIntent.type = "text/csv"
startActivity(Intent.createChooser(sendIntent, "SHARE"))
}
}
答案 0 :(得分:1)
写入文件后,必须将其关闭:
fileWriter.close()
并进行更改:
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(qponFile))
答案 1 :(得分:0)
val HEADER = "Name, DateTime"
var filename = "export.csv"
var path = getExternalFilesDir(null) //get file directory for this package
//(Android/data/.../files | ... is your app package)
//create fileOut object
var fileOut = File(path, filename)
//delete any file object with path and filename that already exists
fileOut.delete()
//create a new file
fileOut.createNewFile()
//append the header and a newline
fileOut.appendText(HEADER)
fileOut.appendText("\n")
// trying to append some data into csv file
fileOut.appendText("Haider, 12/01/2021")
fileOut.appendText("\n")
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileOut))
sendIntent.type = "text/csv"
startActivity(Intent.createChooser(sendIntent, "SHARE"))