Java 使用 FileWriter 和 FileReader 读写图片 - 完整示例和最佳实践
要使用FileWriter和FileReader来读写一张图片,需要先将图片转换成字节数组,然后将字节数组写入文件,或者从文件中读取字节数组并转换成图片。\n\n以下是一个示例代码,演示了如何使用FileWriter和FileReader读写一张图片:\n\njava\nimport java.io.*;\n\npublic class ImageReadWriteExample {\n public static void main(String[] args) {\n String imagePath = "path/to/image.jpg";\n String outputImagePath = "path/to/output.jpg";\n\n // 读取图片并转换成字节数组\n byte[] imageBytes = readImageToBytes(imagePath);\n\n // 将字节数组写入文件\n writeBytesToFile(imageBytes, outputImagePath);\n\n // 从文件中读取字节数组并转换成图片\n byte[] readBytes = readBytesFromFile(outputImagePath);\n writeBytesToImage(readBytes, "path/to/output_image.jpg");\n }\n\n // 读取图片并转换成字节数组\n private static byte[] readImageToBytes(String imagePath) {\n byte[] imageBytes = null;\n try {\n File imageFile = new File(imagePath);\n FileInputStream fis = new FileInputStream(imageFile);\n imageBytes = new byte[(int) imageFile.length()];\n fis.read(imageBytes);\n fis.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return imageBytes;\n }\n\n // 将字节数组写入文件\n private static void writeBytesToFile(byte[] bytes, String outputPath) {\n try {\n FileWriter fileWriter = new FileWriter(outputPath);\n fileWriter.write(new String(bytes));\n fileWriter.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // 从文件中读取字节数组\n private static byte[] readBytesFromFile(String filePath) {\n byte[] bytes = null;\n try {\n File file = new File(filePath);\n FileReader fileReader = new FileReader(file);\n BufferedReader bufferedReader = new BufferedReader(fileReader);\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line);\n }\n bufferedReader.close();\n bytes = stringBuilder.toString().getBytes();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return bytes;\n }\n\n // 将字节数组转换成图片并保存\n private static void writeBytesToImage(byte[] bytes, String outputPath) {\n try {\n FileOutputStream fos = new FileOutputStream(outputPath);\n fos.write(bytes);\n fos.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\n\n请注意,这种方法适用于读写小型图片,对于大型图片可能会导致内存问题。在处理大型图片时,建议使用BufferedInputStream和BufferedOutputStream来读写字节数组。
原文地址: https://www.cveoy.top/t/topic/qsd9 著作权归作者所有。请勿转载和采集!