byte[] 到 Java 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4350084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:23:04  来源:igfitidea点击:

byte[] to file in Java

javaarraysfileioinputstream

提问by elcool

With Java:

使用 Java:

I have a byte[]that represents a file.

我有一个byte[]代表文件的。

How do I write this to a file (ie. C:\myfile.pdf)

我如何将其写入文件(即。C:\myfile.pdf

I know it's done with InputStream, but I can't seem to work it out.

我知道它是用 InputStream 完成的,但我似乎无法解决。

采纳答案by bmargulies

Use Apache Commons IO

使用Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Or, if you insist on making work for yourself...

或者,如果你坚持为自己工作......

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}

回答by Gareth Davis

Try an OutputStreamor more specifically FileOutputStream

尝试一个OutputStream或更具体的FileOutputStream

回答by Powerlord

I know it's done with InputStream

我知道它是用 InputStream 完成的

Actually, you'd be writingto a file output...

其实,你会一个文件输出...

回答by barti_ddu

Basic example:

基本示例:

String fileName = "file.test";

BufferedOutputStream bs = null;

try {

    FileOutputStream fs = new FileOutputStream(new File(fileName));
    bs = new BufferedOutputStream(fs);
    bs.write(byte_array);
    bs.close();
    bs = null;

} catch (Exception e) {
    e.printStackTrace()
}

if (bs != null) try { bs.close(); } catch (Exception e) {}

回答by SharkAlley

Without any libraries:

没有任何库:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}

With Google Guava:

使用谷歌番石榴

Files.write(bytes, new File(path));

With Apache Commons:

使用Apache Commons

FileUtils.writeByteArrayToFile(new File(path), bytes);

All of these strategies require that you catch an IOException at some point too.

所有这些策略都要求您在某个时候也捕获 IOException。

回答by Voicu

From Java 7onward you can use the try-with-resourcesstatement to avoid leaking resources and make your code easier to read. More on that here.

Java 7开始,您可以使用try-with-resources语句来避免资源泄漏并使代码更易于阅读。更多关于这里

To write your byteArrayto a file you would do:

要将您byteArray的文件写入文件,您可以执行以下操作:

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}

回答by TBieniek

Another solution using java.nio.file:

使用的另一种解决方案java.nio.file

byte[] bytes = ...;
Path path = Paths.get("C:\myfile.pdf");
Files.write(path, bytes);

回答by EngineerWithJava54321

Also since Java 7, one line with java.nio.file.Files:

同样从 Java 7 开始,一行带有 java.nio.file.Files:

Files.write(new File(filePath).toPath(), data);

Where data is your byte[] and filePath is a String. You can also add multiple file open options with the StandardOpenOptions class. Add throws or surround with try/catch.

其中 data 是您的 byte[] 并且 filePath 是一个字符串。您还可以使用 StandardOpenOptions 类添加多个文件打开选项。使用 try/catch 添加投掷或环绕。

回答by Yogi

This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.

这是一个程序,我们使用 String Builder 读取和打印字节偏移量和长度数组,并将字节偏移量长度数组写入新文件。

`Enter code here

`在此处输入代码

import java.io.File;   
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;        

//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//     

public class ReadandWriteAByte {
    public void readandWriteBytesToFile(){
        File file = new File("count.char"); //(abcdefghijk)
        File bfile = new File("bytefile.txt");//(New File)
        byte[] b;
        FileInputStream fis = null;              
        FileOutputStream fos = null;          

        try{               
            fis = new FileInputStream (file);           
            fos = new FileOutputStream (bfile);             
            b = new byte [1024];              
            int i;              
            StringBuilder sb = new StringBuilder();

            while ((i = fis.read(b))!=-1){                  
                sb.append(new String(b,5,5));               
                fos.write(b, 2, 5);               
            }               

            System.out.println(sb.toString());               
        }catch (IOException e) {                    
            e.printStackTrace();                
        }finally {               
            try {              
                if(fis != null);           
                    fis.close();    //This helps to close the stream          
            }catch (IOException e){           
                e.printStackTrace();              
            }            
        }               
    }               

    public static void main (String args[]){              
        ReadandWriteAByte rb = new ReadandWriteAByte();              
        rb.readandWriteBytesToFile();              
    }                 
}                

O/P in console : fghij

控制台中的 O/P : fghij

O/P in new file :cdefg

新文件中的 O/P :cdefg

回答by Piyush Rumao

File f = new File(fileName);    
byte[] fileContent = msg.getByteSequenceContent();    

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}