背景
一些很基础的东西,往往用起来,找起来,乱七八糟,所以特此记录
环境
win10,jdk8+,as4+
备注
不考虑安卓沙箱机制,这里讲解的是思路,示例中,是以应用内部目录进行测试
开发
把一个文件,复制到另外一个目录
这里是比较简单的,注意的点就是:
(1)判断目表目录是否存在,否则创建后再进行复制
(2)源文件是否存在
核心代码如下:
public static boolean copyFile(String sourceFilePath, String targetFolderPath) {try {new File(targetFolderPath).mkdirs();File sourceFile = new File(sourceFilePath);File targetFile = new File(targetFolderPath,sourceFile.getName());InputStream in = new FileInputStream(sourceFile);OutputStream out = new FileOutputStream(targetFile);byte[] buffer = new byte[1024];int length;while ((length = in.read(buffer)) > 0) {out.write(buffer, 0, length);}in.close();out.close();return true;} catch (IOException e) {e.printStackTrace();return false;}}
把一个文件夹里面的东西,复制到另外一个文件夹
这里去看网上的资料,大坑,迫不得已,花费了几十分钟踩坑,才得出这个方法。
思路如下:
基础文件判断
(1)判断目标文件夹是否存在,否则创建
(2)判断源文件夹是否存在,否则报错
判断是目录还是文件
首先,这里要有一个思想,就是如果是复制源是一个目录,那么我们对应的目标源,也应该有一个目录,然后后续再把目录里面的东西复制进去。如果复制源是文件,那么直接复制即可
那么,是不是又涉及到了一个递归逻辑,就是:
如果是目录,就目标源创建后递归数据,如果是文件,则复制?
核心代码如下:
public static void copyFolder(File sourceFolder, File targetFolder) {if (sourceFolder.isDirectory()) {if (!targetFolder.exists()) {targetFolder.mkdirs();}String[] files = sourceFolder.list();if (files != null) {for (String file : files) {File sourceFile = new File(sourceFolder, file);File targetFile = new File(targetFolder, file);if (sourceFile.isDirectory()) {targetFile.mkdirs();}copyFolder(sourceFile, targetFile);}}} else {try {FileInputStream fis = new FileInputStream(sourceFolder);FileOutputStream fos = new FileOutputStream(targetFolder);byte[] buffer = new byte[1024];int length;while ((length = fis.read(buffer)) > 0) {fos.write(buffer, 0, length);}fis.close();fos.close();} catch (IOException e) {e.printStackTrace();}}}
上述的方法,进行实际测试,效果良好,如有问题,可以及时反馈!!!
tha’s all-----------------------------------------------------------------------------