Классы FileOutputStream и FileInputStream представляют собой байтовые потоки, ассоциированные с файлами. Позволяют читать и писать байты и массивы байтов в файлы. Пример:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javainputoutput;
/** * * @author martyshov */ import java.io.*; import java.nio.*;
public class JavaInputOutput {
/** * @param args the command line arguments */ public static void main(String[] args) throws IOException {
//описание файла File f = new File("C:/test_streams.txt"); //если нет файла - создаем if (!f.exists()) { f.createNewFile(); } //делаем доступным для записи f.setWritable(true);
//создаем поток и выводим строку FileOutputStream fos = new FileOutputStream(f);
try { byte[] byte_arr = {1, 2, 3, 125, 11, 45, 77}; //пишем массив байтов fos.write(byte_arr); //пишем байт в поток fos.write(111);
} catch (IOException e) { System.err.println(e.getLocalizedMessage()); } finally { fos.close(); }
FileInputStream fis = new FileInputStream(f);
try { //выводим из потока посимвольно Integer ch; while ((ch = fis.read()) != -1) { System.out.print(ch.toString() + ", "); }
System.out.println("\n"); } catch (IOException e) { System.err.println(e.getLocalizedMessage()); } finally { fis.close(); }
}
}
|