Java读取本地文件并转换为字节流:示例代码及详解
以下是一个示例代码,演示如何使用Java读取本地文件并将其转换为字节流,然后将字节流打印并保存为文件:\n\njava\nimport java.io.*;\n\npublic class FileByteStreamExample {\n public static void main(String[] args) {\n String filePath = "path/to/your/file.txt";\n String outputFilePath = "path/to/your/output.txt";\n\n try {\n // 读取本地文件\n File file = new File(filePath);\n FileInputStream fis = new FileInputStream(file);\n\n // 创建字节输出流,用于保存字节流\n FileOutputStream fos = new FileOutputStream(outputFilePath);\n\n // 创建字节数组,用于存储读取的字节\n byte[] buffer = new byte[1024];\n int bytesRead;\n\n // 读取字节流并打印\n while ((bytesRead = fis.read(buffer)) != -1) {\n System.out.write(buffer, 0, bytesRead);\n fos.write(buffer, 0, bytesRead);\n }\n\n // 关闭流\n fis.close();\n fos.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\n\n请将 filePath 替换为要读取的本地文件路径,将 outputFilePath 替换为要保存字节流的文件路径。运行代码后,字节流将被打印到控制台,并保存为指定的文件中。
原文地址: https://www.cveoy.top/t/topic/pEvv 著作权归作者所有。请勿转载和采集!