add directory copying on SD card

This commit is contained in:
tibbi 2016-11-05 19:37:03 +01:00
parent f8e855ec15
commit 7d08cd8653
1 changed files with 51 additions and 25 deletions

View File

@ -36,22 +36,45 @@ class CopyTask(listener: CopyTask.CopyListener, val context: Context) : AsyncTas
@Throws(Exception::class)
private fun copy(source: File, destination: File) {
if (source.isDirectory) {
if (!destination.exists() && !destination.mkdirs()) {
copyDirectory(source, destination)
} else {
copyFile()
}
}
private fun copyDirectory(source: File, destination: File) {
if (!destination.exists()) {
if (Utils.needsStupidWritePermissions(context, destination.absolutePath)) {
val document = Utils.getFileDocument(context, destination.absolutePath)
document.createDirectory(destination.name)
} else if (!destination.mkdirs()) {
throw IOException("Could not create dir " + destination.absolutePath)
}
}
val children = source.list()
for (child in children) {
if (Utils.needsStupidWritePermissions(context, destination.absolutePath)) {
var document = Utils.getFileDocument(context, destination.absolutePath)
document = document.createFile("", child)
val inputStream = FileInputStream(File(source, child))
val out = context.contentResolver.openOutputStream(document.uri)
copyStream(inputStream, out)
} else {
copy(File(source, child), File(destination, child))
}
} else {
}
}
private fun copyFile(source: File, destination: File) {
val directory = destination.parentFile
if (!directory.exists() && !directory.mkdirs()) {
throw IOException("Could not create dir " + directory.absolutePath)
}
val inputStream = FileInputStream(source)
var out: OutputStream?
val out: OutputStream?
if (Utils.needsStupidWritePermissions(context, destination.absolutePath)) {
var document = Utils.getFileDocument(context, destination.absolutePath)
document = document.createFile("", destination.name)
@ -60,14 +83,17 @@ class CopyTask(listener: CopyTask.CopyListener, val context: Context) : AsyncTas
out = FileOutputStream(destination)
}
copyStream(inputStream, out)
}
private fun copyStream(inputStream: InputStream, out: OutputStream?) {
val buf = ByteArray(1024)
var len: Int
while (true) {
len = inputStream.read(buf)
if (len <= 0)
break
out!!.write(buf, 0, len)
}
out?.write(buf, 0, len)
}
}