Le istruzioni che leggono il file con InputStream sono:
inputStream.read(bytes);
Per scrivere su un file con OutputStream:
outputStream.write(bytes, off, len);// scrive un array di byte di lunghezza len a partire da posizione off
Esempio completo:
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();
}
}
}
}
}