bajt [] do pliku w Javie

Z Javą:

Mam byte[], który reprezentuje plik.

Jak napisać to do pliku (tj. C:\myfile.pdf)

Wiem, że to jest zrobione z InputStream, ale nie mogę tego rozgryźć.
Author: naXa, 2010-12-03

12 answers

Use Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Albo, jeśli nalegasz na pracę dla siebie...
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
}
 553
Author: bmargulies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-06 13:16:51

Bez bibliotek:

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

Z Google Guava :

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

Z Apache Commons :

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

Wszystkie te strategie wymagają, aby złapać IOException w pewnym momencie zbyt.

 206
Author: SharkAlley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-27 18:37:43

Inne rozwiązanie za pomocą java.nio.file:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
 134
Author: TBieniek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-18 16:19:34

Również od Javy 7, jedna linia z Javą.nio.plik.Pliki:

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

Gdzie data jest Twoim bajtem [], a filePath jest łańcuchem znaków. Możesz również dodać wiele opcji otwierania plików za pomocą klasy StandardOpenOptions. Dodaj rzuty lub otocz za pomocą try/catch.

 40
Author: EngineerWithJava54321,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-29 13:06:22

Od Java 7 dalej możesz użyć try-with-resources , aby uniknąć wycieku zasobów i ułatwić odczyt kodu. Więcej na ten temat tutaj .

Aby zapisać byteArray do pliku, który wykonasz:

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}
 19
Author: Voicu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-03 00:02:07

Spróbuj OutputStream a dokładniej FileOutputStream

 4
Author: Gareth Davis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-03 21:40:25

I know it ' s done with InputStream

W rzeczywistości, będziesz zapisywać do pliku wyjściowego ...

 1
Author: Powerlord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-03 21:41:08

Przykład podstawowy:

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) {}
 1
Author: barti_ddu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-03 21:52:12
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
Author: Piyush Rumao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-29 13:31:25

////////////////////////// 1] plik do bajtu [] ///////////////////

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] bajt [] do pliku ///////////////////////////

 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
Author: Piyush Rumao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-29 14:05:24

Jest to program, w którym odczytujemy i drukujemy tablicę bajtów offsetu i długości Za pomocą String Builder i zapisujemy tablicę bajtów offsetu długości do nowego pliku.

`Wpisz tutaj kod

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

O / P w Nowym pliku: cdefg

 0
Author: Yogi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-22 18:00:57

Możesz spróbować Cactoos :

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

Więcej Szczegółów: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html

 0
Author: yegor256,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-27 13:00:13