将Byte[]数组保存为PNG至SMB2服务器时出现0KB无效文件问题
问题分析与解决方案
你的代码存在两个核心问题:
- 文件名异常:直接拼接
bytes(AsyncTask的可变参数,本质是byte数组的数组)时,Java会调用数组的toString()方法,返回类似[B@xxxxxx的对象标识,导致文件名错误。 - 文件大小为0KB:仅调用
createNewFile()创建了空文件,但没有将图片的byte数组写入到文件中。
修改后的代码
写入SMB服务器的异步任务类
private class MyCopy extends AsyncTask<byte[], String, String> { @Override protected String doInBackground(byte[]... bytes) { String z = ""; // 取出传入的图片byte数组(可变参数的第一个元素) byte[] imageBytes = bytes[0]; try { // 用时间戳生成唯一文件名,避免重复和标识异常 String fileName = "logbook_image_" + System.currentTimeMillis() + ".png"; String url = "smb://000.000.0.000/spm/Image/" + fileName; NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication( null, "********", "**********"); SmbFile sfile = new SmbFile(url, auth); if (!sfile.exists()) { sfile.createNewFile(); // 将byte数组写入SMB文件,自动关闭流 try (SmbFileOutputStream outputStream = new SmbFileOutputStream(sfile)) { outputStream.write(imageBytes); outputStream.flush(); } z = "文件创建并写入成功!"; } else { z = "该位置已存在同名文件!"; } } catch (Exception ex) { z = ex.getMessage(); } return z; } @Override protected void onPreExecute() { super.onPreExecute(); // 可选:添加加载提示,如显示ProgressDialog } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // 可选:在UI线程提示操作结果,比如Toast // Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); } }
关键修改说明
- 修正文件名逻辑:替换数组拼接为时间戳生成文件名,既解决对象标识问题,又避免文件重名覆盖。如果需要固定文件名,直接替换
fileName为自定义字符串即可。 - 正确获取图片数据:AsyncTask的参数是可变参数类型,需要通过
bytes[0]获取传入的图片byte数组。 - 补充文件写入逻辑:通过
SmbFileOutputStream将byte数组写入SMB文件,使用try-with-resources语法自动管理流资源,防止泄漏。 - 完善生命周期方法:补充
super调用,可按需添加UI交互提示。
内容的提问来源于stack exchange,提问作者Ryan Baltazar
相关产品推荐
相关产品推荐

