输出Log到文件、中文乱码、BIN文件、TXT文件

本文介绍了一种在Android环境中实现日志记录的方法,包括初始化日志目录、将文本日志和二进制日志写入文件的具体实现。通过提供的方法可以方便地管理和查看应用程序运行时产生的各种日志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、初始化目录:

public void init() {
    logPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "aa";
    Log.d(TAG, "logPath : " + logPath);
    File file = new File(logPath);
    if (!file.isDirectory()) {
        boolean make = file.mkdirs();
        Log.d(TAG, "make dirs : " + make);
    }
}

2、根据文件名和输出log输出txt文件

public void logToFile(String fileName, String log) {
    BufferedWriter fw = null;
    try {
        String filePath = logPath + File.separator + fileName;

        File file = new File(filePath);
        Log.d(TAG, "file path : " + filePath+" , file : "+file.exists());
        fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"));
        fw.write(log + "\n"); // 写入文件
        fw.flush(); // 刷新该流的缓冲
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG,"error : "+e);
        try {
            if (fw != null)
                fw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

3、输出到Bin文件

public void logToFileBin(int index, byte[] log) {
    String fileStr ="随机数_" + index + ".bin";
    DataOutputStream dataOutputStream = null;
    FileOutputStream outputStream = null;
    try {
        String filePath = logPath + File.separator + fileStr;
        outputStream = new FileOutputStream(filePath);
        dataOutputStream = new DataOutputStream(new FileOutputStream(filePath));
        dataOutputStream.write(log);
        dataOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG,"error : "+e);
    }finally {
        try {
            if (outputStream != null)
                outputStream.close();
            if (dataOutputStream != null)
                dataOutputStream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
使用时,先初始化,创建文件夹,在每次输入文件时,直接调用方法即可!







### 实现 UniApp 中 gbx.bin 文件的上传功能 #### 选择文件 为了允许用户选择本地文件并准备其用于上传,可以利用 `<input type="file">` HTML 元素来创建一个简单的界面组件。此方法不仅适用于 `.bin` 类型文件的选择,也兼容其他类型的文件。 ```html <template> <view class="container"> <!-- 使用 input[type=file] 来让用户选择要上传的 .bin 文件 --> <input id="uploadFile" type="file" accept=".bin" @change="handleFileChange"/> <button @click="submitFile()">提交</button> </view> </template> <script> export default { data() { return { selectedFile: null, }; }, methods: { handleFileChange(event) { this.selectedFile = event.target.files[0]; } } } </script> ``` 上述代码片段展示了如何监听 `input` 的 change 事件以捕获所选文件,并将其存储于 Vue 组件的数据属性中以便后续操作[^1]。 #### 处理文件 当选择了目标文件之后,在实际发送之前可能还需要做一些预处理工作,比如验证文件大小不超过服务器端设定的最大限制、确认 MIME 类型匹配预期等。这些检查有助于减少不必要的网络传输开销和潜在的安全风险。 考虑到 Windows 对文件名及路径采用 GBK 编码保存的情况,如果遇到乱码问题,则可以在读取或设置文件名称时应用相应的编码转换逻辑: ```javascript methods: { async submitFile() { const formData = new FormData(); // 如果有必要的话,这里可以根据实际情况调整字符集编码 let fileName = encodeURI(this.selectedFile.name); formData.append('gbxFile', this.selectedFile, fileName); try { await uni.uploadFile({ url: 'http://your.server.com/upload', filePath: this.selectedFile.path || '', // 注意不同平台下获取 file path 方式的差异 name: 'file', formData: formData, success(res){ console.log(`Upload succeeded with response ${res.data}`); }, fail(err){ console.error(`Failed to upload due to error:`, err); } }); } catch (error) { console.error(error.message); } } } ``` 这段脚本说明了怎样构建表单数据对象并将选定的二进制文件附加进去;同时也包含了调用 `uni.uploadFile()` 方法向指定 URL 发送 POST 请求的过程。 #### 发送到服务器的最佳实践 确保 API 接口设计合理,支持大文件分片上传机制,从而提高成功率尤其是面对不稳定连接环境下的大型文件传输场景。另外,应当考虑实施进度条反馈给前端用户体验更友好。最后,务必遵循 RESTful 原则定义清晰的状态码返回规则,便于客户端解析响应结果做出适当反应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值