wjc
2025-05-07 b9cc7390e8e8ce64c41c26fb369c98ce669d660c
app/src/main/java/com/hdl/photovoltaic/other/HdlFileLogic.java
@@ -1,24 +1,41 @@
package com.hdl.photovoltaic.other;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.os.Environment;
import android.text.TextUtils;
import com.hdl.photovoltaic.HDLApp;
import com.hdl.photovoltaic.config.ConstantManage;
import com.hdl.photovoltaic.config.UserConfigManage;
import com.hdl.photovoltaic.utils.LocalManageUtil;
import org.apache.commons.io.FileUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
/**
 * 文件界面的逻辑
 * 文件操作的逻辑
 */
public class HdlFileLogic {
    private static volatile HdlFileLogic sHdlFileLogic;
    /**
     * 表示0.5m大小数据
     */
    private final double mDataSize = 0.5;
    /**
     * 获取当前对象
@@ -39,122 +56,531 @@
    private static final String TAG = "FileUtils";
    public static final String userId = "";
    private String getUserId() {
        return UserConfigManage.getInstance().getUserId();
    }
    private String getHomeId() {
        return UserConfigManage.getInstance().getHomeId();
    }
    //region    ---------root路径-----------
    /**
     * 获取内部存储文件路径
     * 获取手机内部存储文件路径
     */
    private String getInternalStoreFilesPath() {
        return HDLApp.getInstance().getFilesDir().getAbsolutePath();
    public String getAPPInternalStoreFilesPath() {
        return Objects.requireNonNull(HDLApp.getInstance().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)).getPath();
    }
    /**
     * 获取App存放文件的根路径
     * 获取存放【用户文件夹】根路径
     */
    public String getAppFilesPath() {
        return HDLApp.getInstance().getFilesDir().getAbsolutePath() + userId + "/home";
    public String getCurrentUserRootPath() {
        return getAPPInternalStoreFilesPath() + "/" + getUserId();
    }
    public File createFile(String dirPath, String fileName) {
    /**
     * 获取存放【住宅文件夹】根路径
     */
    public String getCurrentHomeRootPath() {
        return getCurrentUserRootPath() + "/" + "home_" + getHomeId();
    }
    /**
     * 获取存放【驱动文件夹】根路径
     */
    public String getDriveRootPath() {
        return getAPPInternalStoreFilesPath() + "/upgrade/drive";
    }
    /**
     * 获取存放【固件文件夹】根路径
     */
    public String getFirmwareRootPath() {
        return getAPPInternalStoreFilesPath() + "/upgrade/firmware";
    }
    /**
     * 获取中文【json资源文件夹】全路径
     *
     * @param deviceModel 设备型号
     */
    public String getHdlESLocalJsonZhRootPath(String deviceModel) {
        return getAPPInternalStoreFilesPath() + "/hdlESLocalJson/" + LocalManageUtil.zh + "/" + deviceModel;
    }
    /**
     * 获取英文【json资源文件夹】全路径
     *
     * @param deviceModel 设备型号
     */
    public String getHdlESLocalJsonEnRootPath(String deviceModel) {
        return getAPPInternalStoreFilesPath() + "/hdlESLocalJson/" + LocalManageUtil.en + "/" + deviceModel;
    }
    /**
     * 获取【日志文件】全路径
     */
    public String getLogFileNamePath() {
        return getCurrentHomeRootPath() + "/log.txt";
    }
    /**
     * 获取【用户文件】全路径
     */
    public String getUserFilePath() {
        return getAPPInternalStoreFilesPath() + "/userConfigManage.txt";
    }
    /**
     * 获取中文【json资源文件】全路径
     */
    public String getHdlESLocalJsonZhFilePath(String deviceModel, String fileName) {
        if (!fileName.endsWith(".json")) {
            fileName += ".json";
        }
        return getAPPInternalStoreFilesPath() + "/hdlESLocalJson/" + LocalManageUtil.zh + "/" + deviceModel + "/" + fileName;
    }
    /**
     * 获取英文【json资源文件】全路径
     */
    public String getHdlESLocalJsonEnFilePath(String deviceModel, String fileName) {
        if (!fileName.endsWith(".json")) {
            fileName += ".json";
        }
        return getAPPInternalStoreFilesPath() + "/hdlESLocalJson/" + LocalManageUtil.en + "/" + deviceModel + "/" + fileName;
    }
    /**
     * 获取驱动升级文件全路径
     *
     * @param driverCode 驱动编码
     * @param version    驱动版本
     * @return 全路径
     */
    public String getDrivePathFileName(String driverCode, String version) {
        String fileName = driverCode + "_" + version + ".zip";
        return HdlFileLogic.getInstance().getDriveRootPath() + "/" + fileName;
    }
    /**
     * 获取固件升级文件全路径
     *
     * @param imageId 镜像id
     * @param version 驱动版本
     * @return 全路径
     */
    public String getFirmwarePathFileName(String imageId, String version) {
        String fileName = imageId + "_" + version + ".zip";
        return HdlFileLogic.getInstance().getFirmwareRootPath() + "/" + fileName;
    }
    //endregion
    //region    ---------【文件夹】操作-----------
    /**
     * 预创建文件夹
     */
    public void createDirectory() {
        //存放住宅信息
        this.createFileDir(this.getCurrentHomeRootPath());
        //驱动文件
        this.createFileDir(this.getDriveRootPath());
        //固件文件
        this.createFileDir(this.getFirmwareRootPath());
    }
    /**
     * 预创建json资源文件夹
     */
    public void createHdlESLocalJsonDirectory() {
        //中文文件夹
        this.createFileDir(this.getHdlESLocalJsonZhRootPath(HdlESLocalJsonLogic.DeviceModel.INV));//逆变器
        this.createFileDir(this.getHdlESLocalJsonZhRootPath(HdlESLocalJsonLogic.DeviceModel.LC));//负载中心
        this.createFileDir(this.getHdlESLocalJsonZhRootPath(HdlESLocalJsonLogic.DeviceModel.INV_BMS));//BMS
        this.createFileDir(this.getHdlESLocalJsonZhRootPath(HdlESLocalJsonLogic.DeviceModel.INV_BATTERY));//电池包
        //离线逆变器
        this.createFileDir(this.getHdlESLocalJsonZhRootPath(HdlESLocalJsonLogic.DeviceModel.OFF_INV));//离线逆变器
        this.createFileDir(this.getHdlESLocalJsonZhRootPath(HdlESLocalJsonLogic.DeviceModel.OFF_INV_BMS));//离网逆变器虚拟BMS
        this.createFileDir(this.getHdlESLocalJsonZhRootPath(HdlESLocalJsonLogic.DeviceModel.OFF_INV_BATTERY));//离网逆变器电池包
        //英文文件夹
        this.createFileDir(this.getHdlESLocalJsonEnRootPath(HdlESLocalJsonLogic.DeviceModel.INV));
        this.createFileDir(this.getHdlESLocalJsonEnRootPath(HdlESLocalJsonLogic.DeviceModel.LC));
        this.createFileDir(this.getHdlESLocalJsonEnRootPath(HdlESLocalJsonLogic.DeviceModel.INV_BMS));
        this.createFileDir(this.getHdlESLocalJsonEnRootPath(HdlESLocalJsonLogic.DeviceModel.INV_BATTERY));
        //离线逆变器
        this.createFileDir(this.getHdlESLocalJsonEnRootPath(HdlESLocalJsonLogic.DeviceModel.OFF_INV));//离线逆变器
        this.createFileDir(this.getHdlESLocalJsonEnRootPath(HdlESLocalJsonLogic.DeviceModel.OFF_INV_BMS));//离网逆变器虚拟BMS
        this.createFileDir(this.getHdlESLocalJsonEnRootPath(HdlESLocalJsonLogic.DeviceModel.OFF_INV_BATTERY));//离网逆变器电池包
    }
    /**
     * 创建文件夹
     *
     * @param fullPath fullPath 全路径
     * @return -
     */
    public boolean createFileDir(String fullPath) {
        try {
            File dirFile = new File(dirPath);
            if (!dirFile.exists()) {
                if (!createFileDir(dirFile)) {
                    HdlLogLogic.print(TAG, "createFile dirFile.mkdirs fail");
                    return null;
                }
            } else if (!dirFile.isDirectory()) {
                boolean delete = dirFile.delete();
                if (delete) {
                    return createFile(dirPath, fileName);
                } else {
                    HdlLogLogic.print(TAG, "createFile dirFile !isDirectory and delete fail");
                    return null;
                }
            File file = new File(fullPath);
            if (!file.isDirectory()) {
                boolean succeed = file.mkdirs();
                System.out.println("创建文件夹路径---" + file.getAbsolutePath() + "===创建文件夹结果---" + succeed);
                return succeed;
            }
            File file = new File(dirPath, fileName);
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    Log.e(TAG, "createFile createNewFile fail");
                    return null;
                }
            }
            return file;
            return true;
        } catch (Exception e) {
            HdlLogLogic.print(TAG, "createFile fail :" + e.getMessage());
            e.printStackTrace();
            return null;
            System.out.println("创建文件夹有异常===" + e.getMessage());
            return false;
        }
    }
    /**
     * 删除文件夹
     *
     * @param fullPath 全路径
     */
    public void deleteDirectory(String fullPath) {
        try {
            File fileRoot = new File(fullPath);
            if (fileRoot.isDirectory()) {
                File[] listFiles = fileRoot.listFiles();
                if (listFiles != null) {
                    for (File file : listFiles) {
                        if (file.isDirectory()) {
                            deleteDirectory(file.getAbsolutePath());
                        } else {
                            this.deleteFile(file.getAbsolutePath());
                        }
                    }
                }
            }
            // 删除文件夹本身
            boolean succeed = fileRoot.delete();//文件夹空这个方法才有效
            System.out.println("删除文件夹路径---" + fileRoot.getAbsolutePath() + "===删除结果---" + succeed);
        } catch (Exception e) {
            System.out.println("删除文件夹有异常===" + e.getMessage());
        }
    }
    //endregion
    //region    ---------【文件】操作-----------
    /**
     * 创建文件
     *
     * @param fullPath 全路径
     * @return -
     */
    public boolean createFile(String fullPath) {
        try {
            File file = new File(fullPath);
            if (!file.exists()) {
                boolean succeed = file.createNewFile();
                System.out.println("创建文件路径---" + file.getAbsolutePath() + "===创建文件结果---" + succeed);
                return succeed;
            }
            return true;
        } catch (Exception e) {
            System.out.println("创建文件有异常===" + e.getMessage());
            return false;
        }
    }
    /**
     * 创建文件夹---之所以要一层层创建,是因为一次性创建多层文件夹可能会失败!
     * 删除文件
     *
     * @param fullPath 全路径
     * @return -
     */
    public boolean createFileDir(File dirFile) {
        if (dirFile == null) {
            return true;
        }
        if (dirFile.exists()) {
            return true;
        }
        File parentFile = dirFile.getParentFile();
        if (parentFile != null && !parentFile.exists()) {
            //父文件夹不存在,则先创建父文件夹,再创建自身文件夹
            return createFileDir(parentFile) && createFileDir(dirFile);
        } else {
            boolean mkdirs = dirFile.mkdirs();
            boolean isSuccess = mkdirs || dirFile.exists();
            if (!isSuccess) {
                Log.e("FileUtil", "createFileDir fail " + dirFile);
    public boolean deleteFile(String fullPath) {
        try {
            File file = new File(fullPath);
            if (file.exists()) {
                boolean succeed = file.delete();
                System.out.println("删除文件---" + fullPath + "===结果---" + succeed);
                return succeed;
            }
            return isSuccess;
            return true;
        } catch (Exception e) {
            System.out.println("删除文件有异常===" + e.getMessage());
            return false;
        }
    }
    public void writeFile(String path, String data) {
    /**
     * 写入文件
     *
     * @param fullPath 全路径
     * @param data     数据
     */
    public void writeFile(String fullPath, byte[] data) {
        try {
            File file = new File(path);
            File file = new File(fullPath);
            if (!file.exists()) {
                if (!file.mkdir() && !file.isDirectory()) {
                    HdlLogLogic.print(TAG, "Error: make dir failed!");
                if (!createFile(fullPath)) {
                    //创建失败直接返回
                    return;
                }
            }
            FileOutputStream d = new FileOutputStream(file);
            d.write(data.getBytes());
            d.write(data);
            d.flush();
            d.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("写入文件成功---" + fullPath);
        } catch (Exception e) {
            System.out.println("写入文件有异常---" + e.getMessage());
        }
    }
    public String readFile(String filepath) {
        try {
            String fileContent = "";
            if (null == filepath) {
                Log.d(TAG, "Error: Invalid file name!");
                return fileContent;
            }
    /**
     * 写入文件
     *
     * @param fullPath 全路径
     * @param data     数据
     */
    public void writeFile(String fullPath, String data) {
        writeFile(fullPath, data.getBytes());
    }
            File f = new File(filepath);
    /**
     * 写入文件(一行一行追加内容)
     *
     * @param fullPath 全路径
     * @param dataLine 数据
     */
    public void appendFile(String fullPath, String dataLine) {
        try {
            if (!isBoolean(fullPath)) {
                return;
            }
            File file = new File(fullPath);
            if (!file.exists()) {
                if (!createFile(fullPath)) {
                    //创建失败直接返回
                    return;
                }
            }
            FileOutputStream d = new FileOutputStream(file, true);
            d.write(dataLine.getBytes());
            d.write("\r\n".getBytes());// 写入一个换行
            d.flush();
            d.close();
            if (file.length() > 1024 * 1024 * mDataSize) {
                //文件大于1m,删除文件前100条日志
                this.delFileLien(fullPath, 100);
            }
//            System.out.println("写入一行数据到文件成功---" + dataLine);
        } catch (Exception e) {
            System.out.println("写入一行数据到文件有异常---" + e.getMessage());
        }
    }
    /**
     * 读取文件
     *
     * @param filePath 全路径
     * @return 数据
     */
    public byte[] readFileByte1(String filePath) {
        try {
            if (!isBoolean(filePath)) {
                return null;
            }
            File f = new File(filePath);
            if (!f.exists()) {
                return fileContent;
                return null;
            }
            FileInputStream fis = new FileInputStream(f);
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            byte[] bytes = FileUtils.readFileToByteArray(f);//这个方法不兼用android 6.0
            fis.close();
            fileContent = new String(bytes);
            return fileContent;
            System.out.println("读取文件成功---" + filePath);
            return bytes;
        } catch (Exception e1) {
            e1.printStackTrace();
            Log.d(TAG, "Error: Input File not find!");
            System.out.println("读取文件有异常---" + e1.getMessage());
            return null;
        }
    }
    /**
     * 读取文件
     *
     * @param filePath 全路径
     * @return 数据
     */
    public byte[] readFileByte(String filePath) {
        try {
            if (!isBoolean(filePath)) {
                return null;
            }
            File f = new File(filePath);
            if (!f.exists()) {
                return null;
            }
            FileInputStream fis = new FileInputStream(f);
            BufferedInputStream bis = new BufferedInputStream(fis);
            int fileLength = (int) f.length();
            byte[] bytes = new byte[fileLength];
            int len = bis.read(bytes);
            bis.close();
            fis.close();
            System.out.println("读取文件成功---" + filePath);
            return bytes;
        } catch (Exception e1) {
            System.out.println("读取文件有异常---" + e1.getMessage());
            return null;
        }
    }
    /**
     * 读取文件
     *
     * @param filePath 全路径
     * @return 数据
     */
    public String readFile(String filePath) {
        try {
            byte[] bytes = readFileByte(filePath);
            if (bytes == null) {
                return "";
            }
            return new String(bytes);
        } catch (Exception e1) {
            return "";
        }
    }
    /**
     * 读取文件
     *
     * @param filePath 全路径
     * @return 数据
     */
    public FileInputStream fileStream(String filePath) {
        try {
            if (!isBoolean(filePath)) {
                return null;
            }
            File f = new File(filePath);
            if (!f.exists()) {
                return null;
            }
            fileLength = f.length();
            return new FileInputStream(f);
        } catch (Exception e1) {
            System.out.println("读取文件有异常---" + e1.getMessage());
            return null;
        }
    }
    public static long fileLength = 0;
    /**
     * 指定删除文件行数(从前面删除起)
     *
     * @param filePath   路径
     * @param delLienSum 删除多少行数
     */
    public void delFileLien(String filePath, int delLienSum) {
        if (!isBoolean(filePath)) {
            return;
        }
        //打开文件
        File file = new File(filePath);
        //如果path是传递过来的参数,可以做一个非目录的判断
        if (file.isDirectory()) {
            System.out.println("这是一个目录");
            return;
        }
        StringBuilder content = new StringBuilder(); //文件内容字符串
        try {
            InputStream inputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            int lineCount = 0;
            //分行读取
            while ((line = bufferedReader.readLine()) != null) {
                lineCount += 1;
                if (lineCount > delLienSum) {
                    content.append(line).append("\r\n");
                }
            }
            inputStream.close();
            //删除掉旧文件
            this.deleteFile(filePath);
            //重新创建文件并且写入数据
            this.writeFile(filePath, content.toString());
        } catch (Exception ignored) {
        }
    }
    /**
     * 打开资源文件
     *
     * @param fileName 文件名
     * @param context  上下文
     * @return 返回json字符串
     */
    public String openAssetsFileJson(String fileName, Context context) {
        if (TextUtils.isEmpty(fileName)) {
            return "";
        }
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
    /**
     * 判断路径是否合法
     *
     * @param path 路径
     * @return true合法
     */
    public boolean isBoolean(String path) {
        if (path.contains("//") || path.contains("\\")) {
            System.out.println("无效文件路径---" + path);
            return false;
        }
        return true;
    }
    //endregion
    /**
     * 把位图数据保存到指定路径的图片文件
@@ -171,9 +597,10 @@
            bos.close();
        } catch (Exception e) {
        } catch (Exception ignored) {
        }
    }
    //</editor-fold>
    /**
     * 从指定路径的图片文件中读取位图数据
@@ -187,10 +614,10 @@
            //关闭缓存输入流
            bis.close();
            return bitmap;
        } catch (Exception e) {
        }
        return null;
    }
}