如何使用java将字节数组附加到文件而不覆盖它 [英] how to append a byte array to file without overwriting it using java

查看:25
本文介绍了如何使用java将字节数组附加到文件而不覆盖它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试进行 AES 加密,但正在生成 salt .但是我遇到了一些问题.下面的代码工作正常,但每当我加密第二个等文件时,文件中的盐就会被覆盖.关于如何将盐字节 [] 附加到盐文件而不覆盖它的任何建议?

I trying to make an AES encryption and i am generating a salt . However i had encountered some issue. the below code work fine but whenever i encrypted the second and so on files, the salt in side the file is overwritten. any suggestion on how to append the salt byte [] into the salt fil without overwriting it ?

伙计们..我更新了我的代码..感谢那部分,虽然它修复了覆盖问题,但它没有进入下一行.

Guys..i updated my code..thanks for that portion although it fixed the overwritting issue, it does not make it to next line.

在我的文件中输出:˜V"÷ҲÖ4ô|ŒT‰mÊî0'Z^'û•šÙK·=这是两种盐的组合.

output on my file : ˜V"÷ҲÖ4ô¦ŒT‰mÊî0‘Z^'û•šÙK· = this is two salt combined.

知道如何将其附加到下一行吗?

any idea how to make it append on next line?

我尝试 saltoutfile.write("/n") 但不起作用

i trying saltoutfile.write("/n") but doesnt work

    public byte[] generateSalt() throws IOException{
            //generate Salt value
            // password, iv and salt should be transferred to the other end
            // in a secure manner
            // salt is used for encoding
            // writing it to a file
            // salt should be transferred to the recipient securely
            // for decryption
    byte[] salt = new byte[8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(salt);
            FileOutputStream saltOutFile = new FileOutputStream("C:\\KryptZIP\\salt.enc" , true);
            saltOutFile.write(salt);
        saltOutFile.close();
            return salt;


}

如评论中所述:这是我的读取盐值

as mentioned in comment: this is my read salt value

    public static byte[] readSalt() throws IOException{
    // reading the salt
            // user should have secure mechanism to transfer the
            // salt, iv and password to the recipient
            FileInputStream saltFis = new FileInputStream("C:\\KryptZIP\\salt.enc");
            byte[] salt = new byte[8];
            saltFis.read(salt);
            saltFis.close();
            return salt;
}

推荐答案

您需要使用带有 2 个参数的 FileOutputStream 构造函数.第二个参数是一个布尔标志,指示您是要追加(true)到文件还是从头开始(false).

You need to use the constructor of FileOutputStream with 2 arguments. The second argument is a boolean flag indicating whether you want to append (true) to the file or write from the beginning (false).

将您的代码更改为:

 FileOutputStream saltOutFile = new FileOutputStream("C:\\KryptZIP\\salt.enc", true);

这篇关于如何使用java将字节数组附加到文件而不覆盖它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆