如何在Java中将字节数组写入文件?


71

如何在Java中将字节数组写入文件?


您可以放置​​一些代码并显示要写入文件的内容吗?
Koray Tugay 2015年

Answers:


40

可以使用IOUtils.write(字节[]数据,OutputStream的输出)Apache的百科全书IO

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
FileOutputStream output = new FileOutputStream(new File("target-file"));
IOUtils.write(encoded, output);

63
为什么要为此添加一个第三方库?
jarnbjo

4
OP不询问byteArray的AES编码。
Gaurav Agarwal

@GauravAgarwal不要在他/她原来的问题(他们应该已经更新!),但看到这里的第一和第三点意见: stackoverflow.com/questions/1769776/...
利亚姆

2
@lutz正在为Apache Commons做PR。
CodeBlue 2014年

+1表示FileOutputStream输出= new FileOutputStream(new File(“ target-file”));
bizzr3 2014年

74

正如塞巴斯蒂安·雷德尔(Sebastian Redl)指出的那样,现在最直接的是java.nio.file.Files.write。有关详细信息,请参见“阅读,编写和创建文件”教程


旧答案: FileOutputStream.write(byte []) 将是最直接的。您要写入什么数据?

Java IO系统教程可能对您有用。


字节[]编码= key.getEncoded(); 我需要将编码后的内容写入文本文件
rover12

KeyGenerator kgen = KeyGenerator.getInstance(“ AES”); kgen.init(128); SecretKey键= kgen.generateKey(); 字节[]编码= key.getEncoded();
rover12

然后只需使用FileOutputStream。
Michael Lloyd Lee mlk

+1提及教程...(如果您提到www.google.com,您甚至会得到+
2-

您应该按照@JuanZe的建议将FileOutputStream包装在BufferedOutputStream中。性能要好得多。
山姆·巴纳姆(

32

从Java 1.7开始,有一种新方法: java.nio.file.Files.write

import java.nio.file.Files;
import java.nio.file.Paths;

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);

Java 1.7还解决了Kevin描述的尴尬:现在正在读取文件:

byte[] data = Files.readAllBytes(Paths.get("source-file"));

6
这可能是当今推荐的方法。SecretKey不需要所有的东西;只是打电话Files.write()。谢谢塞巴斯蒂安!
barfuin

16

评论者问“为什么要为此使用第三方库?” 答案是,自己动手实在是太痛苦了。这是一个如何正确执行从文件中读取字节数组的逆操作的示例(对不起,这只是我已经可以使用的代码,并且不像我希望问问者仍要粘贴并使用此代码):

public static byte[] toByteArray(File file) throws IOException { 
   ByteArrayOutputStream out = new ByteArrayOutputStream(); 
   boolean threw = true; 
   InputStream in = new FileInputStream(file); 
   try { 
     byte[] buf = new byte[BUF_SIZE]; 
     long total = 0; 
     while (true) { 
       int r = in.read(buf); 
       if (r == -1) {
         break; 
       }
       out.write(buf, 0, r); 
     } 
     threw = false; 
   } finally { 
     try { 
       in.close(); 
     } catch (IOException e) { 
       if (threw) { 
         log.warn("IOException thrown while closing", e); 
       } else {
         throw e;
       } 
     } 
   } 
   return out.toByteArray(); 
 }

每个人都应该为痛苦感到震惊。

使用优质的图书馆。 毫不奇怪,我推荐Guava的Files.write(byte [],File)


2
令我感到震惊的是这种痛苦,但是这种事情不在标准库中。我们不是在讨论晦涩的文件格式,而是将字节从内存移动到磁盘。
Jim Pivarski 2013年

2
最佳答案:番石榴的Files.write(byte [],File)。
2014年1

12

要将字节数组写入文件,请使用方法

public void write(byte[] b) throws IOException

来自BufferedOutputStream类。

java.io.BufferedOutputStream实现一个缓冲的输出流。通过设置这样的输出流,应用程序可以将字节写入底层输出流,而不必为写入的每个字节引起对底层系统的调用。

对于您的示例,您需要以下内容:

String filename= "C:/SO/SOBufferedOutputStreamAnswer";
BufferedOutputStream bos = null;
try {
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(filename));

//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);

KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
kgen.init(128); 
SecretKey key = kgen.generateKey(); 
byte[] encoded = key.getEncoded();

bos.write(encoded);

} 
// catch and handle exceptions...

1
+1代表BufferedOutputStream。您应该始终将FileOutputStream包装在BufferedOutputStream中,性能要好得多。
Sam Barnum

4
如果要写入的文件只有16个字节的密钥,则将FileOutputStream包裹在BufferedOutputStream中可能比将数据直接写入FileOutputStream慢。
jarnbjo

@SamBarnum你能详细说明吗?为什么将FOS包装在BOS中更快?
theJollySin 2012年

这取决于您使用哪种write()方法。如果您一次(或一小块)写入一个字节,则会导致大量磁盘活动。如果您的磁盘是通过网络安装的,这可能是灾难性的。
山姆·巴纳姆

他确实说过“可能”是灾难性的。男人,该死的开发者总是要挑剔和争论...:P
用户


4

无需外部库就可以轻松完成任务-尤其是在使用Android时。这是解决问题的本机解决方案。这是来自将字节数组存储为图像文件的应用程序的一些代码。

    // Byte array with image data.
    final byte[] imageData = params[0];

    // Write bytes to tmp file.
    final File tmpImageFile = new File(ApplicationContext.getInstance().getCacheDir(), "scan.jpg");
    FileOutputStream tmpOutputStream = null;
    try {
        tmpOutputStream = new FileOutputStream(tmpImageFile);
        tmpOutputStream.write(imageData);
        Log.d(TAG, "File successfully written to tmp file");
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "FileNotFoundException: " + e);
        return null;
    }
    catch (IOException e) {
        Log.e(TAG, "IOException: " + e);
        return null;
    }
    finally {
        if(tmpOutputStream != null)
            try {
                tmpOutputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e);
            }
    }

0
         File file = ...
         byte[] data = ...
         try{
            FileOutputStream fos = FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
         }catch(Exception e){
          }

但是,如果字节数组的长度大于1024,则应使用循环写入数据。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.