package com.tools.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class FileUtil { public static void writeObject2File(Object obj, String path) { File file = new File(path); writeObject2File(obj, file); } /** * 写 object * @param obj * @param file */ public static void writeObject2File(Object obj, File file) { FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(obj); objOut.flush(); objOut.close(); } catch (IOException e) { e.printStackTrace(); } } public static Object readObjectFromFile(String path) { File file = new File(path); return readObjectFromFile(file); } /** * 读取保存的object * @param file * @return */ public static Object readObjectFromFile(File file) { Object temp = null; FileInputStream in; try { in = new FileInputStream(file); ObjectInputStream objIn = new ObjectInputStream(in); temp = objIn.readObject(); objIn.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return temp; } /** * 文件copy * @param oldPath * @param newPath */ public static void copy(String oldPath, String newPath) { FileInputStream fis = null; FileOutputStream fos = null; int byteread = 0; File oldfile = new File(oldPath); try { if (oldfile.exists()) { fis = new FileInputStream(oldPath); fos = new FileOutputStream(newPath); byte[] buffer = new byte[1024]; while ((byteread = fis.read(buffer)) != -1) { fos.write(buffer, 0, byteread); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } }public static File getCacheDir(Context ctx) { File file = ctx.getExternalCacheDir(); if (file == null) { file = ctx.getCacheDir(); } return file; } public static File getImgFileDir(Context ctx) { File file = ctx.getExternalFilesDir(Environment.DIRECTORY_PICTURES); if (file == null) { file = ctx.getFilesDir(); } return file; } public static File getTempDir() { File file = Environment.getExternalStorageDirectory(); File tempDir = new File(file.getAbsoluteFile() + "/iasku/temp/"); if (!tempDir.exists()) { //可以创建当前的file 没有上级目录的 也可以创建 tempDir.mkdirs(); } return tempDir; } public static File getDownloadDir() { String path = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/iasku/downloads/"; File file = new File(path); if (!file.exists()) { file.mkdirs(); } return file; } /** * 音频文件保存路径 * @return */ public static File getDownloadAudioDir() { String path = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/iasku/audio/"; File file = new File(path); if (!file.exists()) { file.mkdirs(); } return file; }}
对文件封装util
最新推荐文章于 2023-02-06 17:43:48 发布