代码片段: FileUtils-FileUtils.java

package util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java...
<pre>package util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; public class FileUtils { public static boolean save(byte[] bytes, String pathname, String fileName) throws IOException { File path = new File(pathname); if (!path.exists()) { path.mkdirs(); } File newFile = new File(path, fileName); if (newFile.exists()) { throw new IOException("文件已存在"); } newFile.createNewFile(); Files.write(newFile.toPath(), bytes); return true; } /** * 删除文件,可以是文件或文件夹 * * @param fileName * 要删除的文件名 * @return 删除成功返回true,否则返回false * @throws IOException */ public static boolean delete(String fileName) throws IOException { File file = new File(fileName); if (file.isFile()) { return Files.deleteIfExists(file.toPath()); } else { return deleteDirectory(fileName); } } /** * 删除目录及目录下的文件 * * @param dir * 要删除的目录的文件路径 * @return 目录删除成功返回true,否则返回false * @throws IOException */ private static boolean deleteDirectory(String dir) throws IOException { if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } File dirFile = new File(dir); if (!dirFile.exists()) { return true; } if (!dirFile.isDirectory()) { return false; } boolean flag = true; // 删除文件夹中的所有文件包括子目录 File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { flag = Files.deleteIfExists(files[i].toPath()); } else if (files[i].isDirectory()) { flag = deleteDirectory(files[i].getAbsolutePath()); } if (!flag) { return flag; } } // 删除当前目录 return dirFile.delete(); } public static byte[] toByteArray(String filename) throws IOException { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } FileChannel channel = null; FileInputStream fs = null; try { fs = new FileInputStream(f); channel = fs.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while ((channel.read(byteBuffer)) > 0) { } return byteBuffer.array(); } finally { channel.close(); fs.close(); } } public static byte[] toByteArray(File file) throws IOException { if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } FileChannel channel = null; FileInputStream fs = null; try { fs = new FileInputStream(file); channel = fs.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while ((channel.read(byteBuffer)) > 0) { } return byteBuffer.array(); } finally { channel.close(); fs.close(); } } } </pre>
  • 发表于 2018-07-06 15:40
  • 阅读 ( 409 )
  • 分类:代码片段

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除