Java 中的 byte[] 到文件

发布于 2024-10-05 18:39:07 字数 142 浏览 1 评论 0原文

对于 Java:

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

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

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

With Java:

I have a byte[] that represents a file.

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

孤独陪着我 2024-10-12 18:39:08

使用 Apache Commons IO

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

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

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
}

Use 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
}
万劫不复 2024-10-12 18:39:08

没有任何库:

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

使用Google Guava

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

使用 Apache Commons

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

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

Without any libraries:

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

With Google Guava:

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

With Apache Commons:

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

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

风轻花落早 2024-10-12 18:39:08

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

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

Another solution using java.nio.file:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
一世旳自豪 2024-10-12 18:39:08

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

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

其中 data 是您的 byte[],filePath 是一个字符串。您还可以使用 StandardOpenOptions 类添加多个文件打开选项。添加 throws 或用 try/catch 包围。

Also since Java 7, one line with 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.

策马西风 2024-10-12 18:39:08

Java 7开始,您可以使用try-with-resources语句来避免资源泄漏并使代码更易于阅读。更多信息请参见此处

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

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

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

To write your byteArray to a file you would do:

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}
零崎曲识 2024-10-12 18:39:08

尝试使用 OutputStream 或更具体地说 FileOutputStream

Try an OutputStream or more specifically FileOutputStream

悸初 2024-10-12 18:39:08

基本示例:

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) {}

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) {}
来日方长 2024-10-12 18:39:08

/////////////////////////// 1] 文件到字节 [] /////////////////// //

Path path = Paths.get(p);
                    byte[] data = null;                         
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                    }

///////////////////////// 2] 字节 [] 到文件 //////////////////// /////////////////

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

////////////////////////// 1] File to Byte [] ///////////////////

Path path = Paths.get(p);
                    byte[] data = null;                         
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                    }

/////////////////////// 2] Byte [] to File ///////////////////////////

 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);
                            }
り繁华旳梦境 2024-10-12 18:39:08
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);
}
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);
}
倾城月光淡如水﹏ 2024-10-12 18:39:08

我知道这是用InputStream完成的

的实际上,你会写入文件输出...

I know it's done with InputStream

Actually, you'd be writing to a file output...

最单纯的乌龟 2024-10-12 18:39:08

在这个程序中,我们使用字符串生成器读取和打印字节偏移量和长度数组,并将字节偏移量长度写入新文件。

`在此处输入代码

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 : fghij

新文件中的 O/P :cdefg

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.

`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 in new file :cdefg

嘿哥们儿 2024-10-12 18:39:08

您可以尝试 Cactoos

new LengthOf(new TeeInput(array, new File("a.txt"))).value();

更多详细信息:http://www.yegor256.com/2017/06/22/object-orient-input-output- in-cactoos.html

You can try Cactoos:

new LengthOf(new TeeInput(array, new File("a.txt"))).value();

More details: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文