是否可以将 FileOutputStream 转换为字节数组?

sha*_*vel 3 android bytearray file fileinputstream

我想将 FileOutputStream 转换为 Byte 数组,以便在两个应用程序之间传递二进制数据。请问有人可以帮忙吗?

Ahm*_*mal 7

要将文件转换为字节数组,请使用 ByteArrayOutputStream 类。这个类实现了一个输出流,其中数据被写入一个字节数组。缓冲区会随着数据写入而自动增长。可以使用 toByteArray() 和 toString() 检索数据。

要将字节数组转换回原始文件,使用 FileOutputStream 类。文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流。

以下代码已经过全面测试。

 public static void main(String[] args) throws FileNotFoundException, IOException {
            File file = new File("java.pdf");

            FileInputStream fis = new FileInputStream(file);
            //System.out.println(file.exists() + "!!");
            //InputStream in = resource.openStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            try {
                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    bos.write(buf, 0, readNum); //no doubt here is 0
                    //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                    System.out.println("read " + readNum + " bytes,");
                }
            } catch (IOException ex) {
                Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
            }
            byte[] bytes = bos.toByteArray();

            //below is the different part
            File someFile = new File("java2.pdf");
            FileOutputStream fos = new FileOutputStream(someFile);
            fos.write(bytes);
            fos.flush();
            fos.close();
        }
Run Code Online (Sandbox Code Playgroud)

如何使用 FileOutputStream 将字节数组写入文件。FileOutputStream 是用于将数据写入 File 或 FileDescriptor 的输出流。

public static void main(String[] args) {

        String s = "input text to be written in output stream";

        File file = new File("outputfile.txt");

        FileOutputStream fos = null;

        try {

            fos = new FileOutputStream(file);

            // Writes bytes from the specified byte array to this file output stream 
            fos.write(s.getBytes());

        }
        catch (FileNotFoundException e) {
            System.out.println("File not found" + e);
        }
        catch (IOException ioe) {
            System.out.println("Exception while writing file " + ioe);
        }
        finally {
            // close the streams using close method
            try {
                if (fos != null) {
                    fos.close();
                }
            }
            catch (IOException ioe) {
                System.out.println("Error while closing stream: " + ioe);
            }

        }

    }
Run Code Online (Sandbox Code Playgroud)