【问题标题】:How can I write a byte array to a file in Java?如何将字节数组写入 Java 中的文件?
【发布时间】:2010-12-18 16:37:45
【问题描述】:

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

【问题讨论】:

  • 你能放一些代码并显示你想要写入文件的具体内容吗?

标签: java


【解决方案1】:

正如Sebastian Redl 指出的最直接的现在java.nio.file.Files.write。这方面的详细信息可以在Reading, Writing, and Creating Files tutorial 中找到。


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

tutorials for Java IO system 可能对您有用。

【讨论】:

  • byte[] 编码 = key.getEncoded();我需要将编码写入文本文件
  • KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey 密钥 = kgen.generateKey(); byte[] 编码 = key.getEncoded();
  • 然后简单地使用 FileOutputStream。
  • +1 用于提及教程...(如果您提及 www.google.com,您甚至会收到 +2 - 好吧,这很讨厌,但这不是流浪者的第一个问题...)
  • 您应该按照@JuanZe 的建议将 FileOutputStream 包装在 BufferedOutputStream 中。性能要好得多。
【解决方案2】:

您可以从Apache Commons IO 使用IOUtils.write(byte[] data, OutputStream output)

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);

【讨论】:

  • 为什么要为此添加第三方库?
  • OP 不询问 byteArray 的 AES 编码。
  • @GauravAgarwal 不在她/他的原始问题中(他们应该更新了!),但请参阅此处的第一条和第三条评论:stackoverflow.com/questions/1769776/…
  • @lutz 正在为 Apache Commons 做 PR。
  • +1 for FileOutputStream 输出 = new FileOutputStream(new File("target-file"));
【解决方案3】:

从 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"));

【讨论】:

  • 这可能是当今推荐的方式。不需要所有SecretKey 的东西;只需致电Files.write()。谢谢塞巴斯蒂安!
【解决方案4】:

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

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)

【讨论】:

  • 我对这是多么痛苦感到震惊,而且这种东西不在标准库中。我们不是在谈论一种晦涩难懂的文件格式,而是将字节从内存移动到磁盘。
  • 最佳答案:Guava 的 Files.write(byte[], File)。
  • 我会在图书馆接受这个答案!您可能对这个问题感兴趣:stackoverflow.com/questions/70074875/…
【解决方案5】:

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

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 用于提及 BufferedOutputStream。您应该始终将 FileOutputStream 包装在 BufferedOutputStream 中,性能要好得多。
  • 如果您要写入文件的只是一个 16 字节的密钥,则将 FileOutputStream 包装在 BufferedOutputStream 中可能比直接将数据写入 FileOutputStream 慢。
  • @SamBarnum 你能详细说明一下吗?为什么将 FOS 封装在 BOS 中更快?
  • 这取决于您使用的 write() 方法。如果您一次写入一个字节(或以小块的形式),则会导致大量磁盘活动。如果您的磁盘是网络安装的,这可能是灾难性的。
  • 好吧,他确实说过“可能”是灾难性的。伙计,该死的开发人员总是很挑剔和争论不休......:P
【解决方案6】:

Apache Commons IO Utils 有一个FileUtils.writeByteArrayToFile() 方法。请注意,如果您正在做任何文件/IO 工作,那么 Apache Commons IO 库将为您做很多工作。

【讨论】:

  • 链接已失效(吉姆)。
【解决方案7】:

不需要外部库来膨胀——尤其是在使用 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);
            }
    }

【讨论】:

    【解决方案8】:
             File file = ...
             byte[] data = ...
             try{
                FileOutputStream fos = FileOutputStream(file);
                fos.write(data);
                fos.flush();
                fos.close();
             }catch(Exception e){
              }
    

    但如果字节数组长度超过 1024,则应使用循环写入数据。

    【讨论】:

      猜你喜欢
      • 2015-09-04
      • 2012-05-14
      • 2019-10-29
      • 2012-04-10
      • 1970-01-01
      • 2014-04-10
      • 2011-08-14
      • 1970-01-01
      • 2016-07-05
      相关资源
      最近更新 更多