kotlin编写的,java的话大体相同
object FileUtils {
@JvmStatic
@Throws(IOException::class)
fun createAndWriteFile(url: String, json: String) {
val path = Paths.get(url)
deleteFile(path)
Files.createFile(path)
Files.newBufferedWriter(path).use { bfw ->
bfw.write(json)
bfw.flush()
}
}
@JvmStatic
@Throws(IOException::class)
fun deleteFile(url: String) {
val path = Paths.get(url)
deleteFile(path)
}
@JvmStatic
@Throws(IOException::class)
fun deleteFile(path: Path) {
try {
Files.deleteIfExists(path)
} catch (e: DirectoryNotEmptyException) {
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
if (exc == null) {
Files.delete(dir)
return super.postVisitDirectory(dir, exc)
} else {
throw exc
}
}
})
}
}
@JvmStatic
fun createDirectory(dirUrl: String) {
val path = Paths.get(dirUrl)
deleteFile(dirUrl)
Files.createDirectory(path)
}
@JvmStatic
fun downloadAndSaveFile(url: String, saveDir: String, fileName: String? = null) {
val saveFileName = fileName ?: url.substring(url.lastIndexOf("/") + 1)
URL(url).openStream().use { ins ->
val target = Paths.get(saveDir, saveFileName)
Files.createDirectories(target.parent)
Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING)
}
}
@JvmStatic
@Throws(IOException::class)
fun zip(targetFile: String, srcDir: String) {
FileOutputStream(targetFile).use { outputStream -> zip(srcDir, outputStream) }
}
@JvmStatic
@Throws(IOException::class)
fun zip(srcDir: String, outputStream: OutputStream) {
BufferedOutputStream(outputStream).use { bufferedOutputStream ->
ZipArchiveOutputStream(bufferedOutputStream).use { out ->
val start = Paths.get(srcDir)
Files.walkFileTree(start, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
FileInputStream(file.toFile()).use { input ->
val entry = ZipArchiveEntry(file.toFile(), start.relativize(file).toString())
out.putArchiveEntry(entry)
IOUtils.copy(input, out)
out.closeArchiveEntry()
}
return super.visitFile(file, attrs)
}
})
}
}
}
}
|