Byte Array Input Stream l Byte Array Input
Классы Byte. Array. Input. Stream l Поток, считывающий (записывающий) данные из массива байт. У класса Byte. Array. Input. Stream конструктор принимает массив byte[]. Тогда при вызове read() данные будут браться из него. byte[] bytes ={1, -1, 0}; Byte. Array. Input. Stream in =new Byte. Array. Input. Stream(bytes); int readed. Int =in. read(); //readed. Int=1 readed. Int =in. read(); //readed. Int=255 readed. Int =in. read(); //readed. Int=0
Пример byte[] bytes. To. Write ={1, 2, 3}; //что записываем byte[] bytes. Readed =new byte[10]; //куда считываем String file. Name ="d: \test. txt"; try { File. Output. Stream out. File =new File. Output. Stream(file. Name); out. File. write(bytes. To. Write); //запись в файл out. File. close(); File. Input. Stream in. File =new File. Input. Stream(file. Name); int bytes. Available =in. File. available(); //сколько можно считать int count =in. File. read(bytes. Readed, 0, bytes. Available); in. File. close(); } catch (File. Not. Found. Exception e){ System. out. println("Невозможно произвести запись в файл: "+file. Name); } catch (IOException e){ System. out. println("Ошибка ввода/вывода: "+e. to. String()); }
Пример File. Input. Stream in. File 1 =null; File. Input. Stream in. File 2 =null; Sequence. Input. Stream sequence. Stream =null; File. Output. Stream out. File =null; in. File 1 =new File. Input. Stream("file 1. txt"); in. File 2 =new File. Input. Stream("file 2. txt"); sequence. Stream =new Sequence. Input. Stream(in. File 1, in. File 2); out. File =new File. Output. Stream("file 3. txt"); int readed. Byte =sequence. Stream. read(); while(readed. Byte!=-1){out. File. write(readed. Byte); readed. Byte =sequence. Stream. read();
Пример на запись и считывание с буферизацией String file. Name ="d: \file 1"; Input. Stream in. Stream =null; Output. Stream out. Stream =null; //Записать в файл некоторое количество байт long time. Start =System. current. Time. Millis(); out. Stream =new File. Output. Stream(file. Name); out. Stream =new Buffered. Output. Stream(out. Stream); for(int i=1000000; --i>=0; ){ out. Stream. write(i); } in. Stream =new File. Input. Stream(file. Name); in. Stream =new Buffered. Input. Stream(in. Stream); while(in. Stream. read()!=-1){… }
Пример на запись и считывание символьного потока String file. Name = "d: \file. txt"; File. Writer fw = null; Buffered. Writer bw = null; File. Reader fr = null; Buffered. Reader br = null; //Строка, которая будет записана в файл String data = "Some data to be written and readed n"; try{ fw = new File. Writer(file. Name); bw = new Buffered. Writer(fw); System. out. println("Write some data to file: " + file. Name); // Несколько раз записать строку for(int i=(int)(Math. random()*10); --i>=0; )bw. write(data); bw. close(); fr = new File. Reader(file. Name); br = new Buffered. Reader(fr); String s = null; int count = 0; System. out. println("Read data from file: " + file. Name); // Считывать данные, отображая на экран while((s=br. read. Line())!=null) System. out. println("row " + ++count + " read: " + s); br. close(); }catch(Exception e){ e. print. Stack. Trace(); }
Чтение символов // Использует Buffered. Reader для чтения символов с консоли, import java. io. *; class BRRead { public static void main(String args [ ]) throws IOException { char c; Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); System. out. println("Введите символы, 'q' - для завершения. "); // чтение символов do { с = (char) br. read(); System. out. println(с); } while(c != 'q'); } }
Чтение строк // Крошечный редактор. import java. io. . *; class Tiny. Edit { public static void main(String args[]; throws IOException ( // Создать Buffered. Reader-объект, используя System. in Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); String str[] = new String[100]; System. out. println("Введите строки текста. "); System. out. println("Введите 'stop' для завершения. "); for (int i=0; i<100; i++) { str[i] = br. read. Line(); if(str[i]. equals("stop")) break; } System. out. println(“n Вот ваш файл: "); // Вывести строки на экран. for (int i=0; i<100; i++) { if(str[i]. equals("stop")) break; System. out. println(str[i]); } }}
Класс Print. Writer // Демонстрирует Printwriter. import java. io. *; public class Print. Writer. Demo { public static void main(String args[j]) { Printwriter pw = new Printwriter(System. out, true); pw. print. In("Это строка: "); int i = -7; pw. println(i); double d = 4. 5 e-7; pw. println(d); } l Вывод этой программы: Это строка: -7 4. 5 Е-7
Пример Сериализация Десериализация Byte. Array. Output. Stream os =new byte[] b. Array =os. to. Byte. Array(); Byte. Array. Output. Stream(); //получение содержимого массива Object obj. Save =new Integer(1); Object. Output. Stream oos =new Object. Output. Stream(os); oos. write. Object(obj. Save); Byte. Array. Input. Stream is =new Byte. Array. Input. Stream(b. Array); Object. Input. Stream ois =new Object. Input. Stream(is); Object obj. Read =ois. read. Object(); При этом объекты равны по значению, но не равны по ссылке!!!
public class Parent{ public String firstname, lastname; public parent(){ firstname=‘old_first’; lastname=‘old_last’; } } public class Child extends Parent implements Serializable{ private int age; public Child (int age){ this. age=age; } }…. File. Output. Stream fos=new File. Output. Stream(“output. bin”); Object. Output. Stream oos=new Object. Output. Stream(fos); Child c= new Child(2); oos. write. Object(c); oos. close(); File. Input. Stream fis=new File. Input. Stream(“output. bin”); Object. Input. Stream ois=new Object. Input. Stream(fis); Ois. read. Object(); ois. close();
- Slides: 42