Read Write File With InputStream OutputStream Java

Le istruzioni che leggono  il  file con InputStream sono:

InputStream inputStream = new FileInputStream(“c:/myFile.txt”);
inputStream.read(bytes);

Per scrivere su un file con OutputStream:

OutputStream outputStream = new FileOutputStream(new File(“c:/myFileNew.txt”));
outputStream.write(bytes, off, len);// scrive un array di byte di  lunghezza len a partire da posizione off

Esempio completo:

package com;

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

public class InputStreamToFile {
    public static void main(String[] args) {

InputStream inputStream = null;
OutputStream outputStream = null;

try {
inputStream = new FileInputStream(“c:/myFile.txt”);

// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(“c:/myFileNew.txt”));

int read = 0;
byte[] bytes = new byte[1024];

while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}

System.out.println(“Done!”);

} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
// outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
    }
}

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *