SlideShare a Scribd company logo

      
       Язык Java 
      
     
      
       Потоки 
       java.io 
      
     
      
       Алексей Бованенко

      
       Введение 
      
     
      
       
        
         Понятие потоков 
        
       
       
        
         
          
           Поток представляет собой набор данных, связанный с источником (поток ввода), либо приемником (поток вывода) 
          
         
        
       
       
        
         
          
           Источник или приемник 
          
         
        
       
       
        
         
          
           
            
             Файлы на диске 
            
           
          
         
        
       
       
        
         
          
           
            
             Устройства 
            
           
          
         
        
       
       
        
         
          
           
            
             Другие программы 
            
           
          
         
        
       
       
        
         
          
           
            
             Буфер в памяти 
            
           
          
         
        
       
       
        
         
          
           Потоки могут содержать данные различных типов 
          
         
        
       
       
        
         
          
           
            
             Примитивные типы 
            
           
          
         
        
       
       
        
         
          
           
            
             Символы 
            
           
          
         
        
       
       
        
         
          
           
            
             Объектные потоки

      
       Потоки в java.io 
      
     
      
       
        
         В java.io определены следующие потоки 
        
       
       
        
         
          
           InputStream / OutputStream 
          
         
        
       
       
        
         
          
           FileInputStream / FileOutputStream 
          
         
        
       
       
        
         
          
           BufferedInputStream / BufferedOutputStream 
          
         
        
       
       
        
         
          
           InputStreamReader / OutputStreamWriter 
          
         
        
       
       
        
         
          
           FileReader / FileWriter 
          
         
        
       
       
        
         
          
           BufferedReader / BufferedWriter 
          
         
        
       
       
        
         
          
           StringReader / StringWriter 
          
         
        
       
       
        
         
          
           DataInputStream / DataOutputStream 
          
         
        
       
       
        
         
          
           ObjectInputStream  / ObjectOutputStream

      
       FileInputStream 
      
     
      
       
        
         class FileInputStream extends InputStream 
        
       
       
        
         public FileInputStream(String name) throws FileNotFoundException 
        
       
       
        
         public FileInputStream(File file) throws FileNotFoundException 
        
       
       
        
         public FileInputStream(FileDescriptor fdObj) 
        
       
       
        
         public native int read() throws IOException 
        
       
       
        
         private native int readBytes(byte b[], int off, int len) throws IOException 
        
       
       
        
         public int read(byte b[]) throws IOException 
        
       
       
        
         public int read(byte b[], int off, int len) throws IOException 
        
       
       
        
         public native long skip(long n) throws IOException 
        
       
       
        
         public native int available() throws IOException 
        
       
       
        
         public void close() throws IOException 
        
       
       
        
         public FileChannel getChannel() 
        
       
       
        
         public boolean markSupported() 
        
       
       
        
         public synchronized void reset() throws IOException 
        
       
       
        
         public synchronized void mark(int readlimit)

      
       FileOutputStream 
      
     
      
       
        
         class FileOutputStream extends OutputStream 
        
       
       
        
         public FileOutputStream(String name) throws  FileNotFoundException 
        
       
       
        
         public FileOutputStream(String name, boolean append)  throws FileNotFoundException 
        
       
       
        
         public FileOutputStream(File file) throws FileNotFoundException 
        
       
       
        
         public FileOutputStream(File file, boolean append) throws FileNotFoundException 
        
       
       
        
         public FileOutputStream(FileDescriptor fdObj) 
        
       
       
        
         public native void write(int b) throws IOException 
        
       
       
        
         public void write(byte b[]) throws IOException 
        
       
       
        
         public void write(byte b[], int off, int len) throws IOException 
        
       
       
        
         public void close() throws IOException 
        
       
       
        
         public void flush() throws IOException

      
       Пример использования (использование методов read() и write(int)) 
      
     
      
       
        
         try{ //  Внешний блок try   try{ //  Создание потока вывода   fo=new FileOutputStream(&quot;out.txt&quot;);   int l=s.length();   int i=0;   while(i<l)   {   fo.write(s.codePointAt(i++));   }   }finally{   if(fo!=null)   fo.close();   }

      
       Пример (продолжение) 
      
     
      
       
        
         try{ //  Создание входного потока   fi=new FileInputStream(&quot;out.txt&quot;);   int i=0;   StringBuilder sb=new StringBuilder();   while((i=fi.read())!=-1)   {   sb.append(Character.toChars(i));   }   System.out.println(&quot;Received from file: &quot;+sb.toString());   }finally{   if(fi!=null)   fi.close();   }   }catch(FileNotFoundException e) //  Перехват для внешнего try   {   System.out.println(e);   }catch(IOException e) //  Перехват для внешнего try   {   System.out.println(e);   }

      
       Пример использования (использование методов read(byte[]) и write(byte[])) 
      
     
      
       
        
         try{  //  Внешний блок try   try{ //  Создание потока вывода   fo=new FileOutputStream(&quot;out.txt&quot;);   int l=s.length();   int i=0;   byte[] b=s.getBytes();   fo.write(b);   }finally{   if(fo!=null)   fo.close();   }

      
       Пример (продолжение) 
      
     
      
       
        
         try{ //  Создание входного потока   fi=new FileInputStream(&quot;out.txt&quot;);   int i=fi.available();   byte[] b=new byte[i];   fi.read(b);   String s1=new String(b);   System.out.println(&quot;Received from file: &quot;+s1);   }finally{   if(fi!=null)   fi.close();   }   }catch(FileNotFoundException e) //  Перехват для внешнего try   {   System.out.println(e);   }catch(IOException e) //  Перехват для внешнего try   {   System.out.println(e);   }

      
       Пример использования (использование методов read(byte[], int, int) и write(byte[], int , int)) 
      
     
      
       
        
         try{ //  Внешний блок try   try{ //  Создание потока вывода   fo=new FileOutputStream(&quot;out.txt&quot;);   int l=s.length();   int i=0;   byte[] b=s.getBytes();   fo.write(b,0,b.length);   }finally{   if(fo!=null)   fo.close();   }

      
       Пример (продолжение) 
      
     
      
       
        
         try{  //  Создание входного потока   fi=new FileInputStream(&quot;out.txt&quot;);   int i=fi.available();   byte[] b=new byte[i];   fi.read(b,0,i);   String s1=new String(b);   System.out.println(&quot;Received from file: &quot;+s1);   }finally{   if(fi!=null)   fi.close();   }   }catch(FileNotFoundException e) //  Перехват для внешнего try   {   System.out.println(e);   }catch(IOException e) //  Перехват для внешнего try   {   System.out.println(e);   }

      
       BufferedInputStream 
      
     
      
       
        
         class BufferedInputStream extends FilterInputStream 
        
       
       
        
         public BufferedInputStream(InputStream in) 
        
       
       
        
         public BufferedInputStream(InputStream in, int size) 
        
       
       
        
         public synchronized int read() throws IOException 
        
       
       
        
         public synchronized int read(byte b[], int off, int len) throws IOException 
        
       
       
        
         public synchronized long skip(long n) throws IOException 
        
       
       
        
         public synchronized int available() throws IOException 
        
       
       
        
         public synchronized void mark(int readlimit) 
        
       
       
        
         public synchronized void reset() throws IOException 
        
       
       
        
         public boolean markSupported() 
        
       
       
        
         public void close() throws IOException

      
       BufferedOutputStream 
      
     
      
       
        
         class BufferedOutputStream extends FilterOutputStream 
        
       
       
        
         public BufferedOutputStream(OutputStream out) 
        
       
       
        
         public BufferedOutputStream(OutputStream out, int size) 
        
       
       
        
         public synchronized void write(int b) throws IOException 
        
       
       
        
         public synchronized void write(byte b[], int off, int len) throws IOException 
        
       
       
        
         public synchronized void flush() throws IOException

      
       Пример использования  BufferedInputStream/BufferedOutputStream 
      
     
      
       
        
         try{ //  Внешний блок try   try{ //  Создание потока для записи файла   bo=new BufferedOutputStream(new FileOutputStream(&quot;out.txt&quot;));   byte[] b=new byte[s.length()];   b=s.getBytes();   bo.write(b,0,b.length);   }finally{   if(bo!=null)   bo.close();   }

      
       Пример использования  (продолжение) 
      
     
      
       
        
         try{  //  Создание потока для чтения   bi=new BufferedInputStream(new FileInputStream(&quot;out.txt&quot;));   int i=bi.available();   byte[] b=new byte[i];   bi.mark(i);   bi.read(b, 0, i);   bi.reset();   String s1=new String(b);   bi.read(b, 0, i);   String s2=new String(b);   System.out.println(s1+&quot; &quot;+s2);   }finally{   if(bi!=null)   bi.close();   }   }catch(Exception e){ //  Перехват для внешнего try   System.out.println(e);   }

      
       InputStreamReader 
      
     
      
       
        
         public class InputStreamReader extends Reader 
        
       
       
        
         public InputStreamReader(InputStream in) 
        
       
       
        
         public InputStreamReader(InputStream in, String charsetName) 
        
       
       
        
         public InputStreamReader(InputStream in, Charset cs) 
        
       
       
        
         public InputStreamReader(InputStream in, CharsetDecoder dec) 
        
       
       
        
         public String getEncoding() 
        
       
       
        
         public int read() throws IOException 
        
       
       
        
         public int read(char cbuf[]) throws IOException 
        
       
       
        
         public int read(char cbuf[], int offset, int length) throws IOException 
        
       
       
        
         public boolean ready() throws IOException 
        
       
       
        
         public void close() throws IOException

      
       OutputStreamWriter 
      
     
      
       
        
         class OutputStreamWriter extends Writer 
        
       
       
        
         public OutputStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException 
        
       
       
        
         public OutputStreamWriter(OutputStream out) 
        
       
       
        
         public OutputStreamWriter(OutputStream out, Charset cs) 
        
       
       
        
         public OutputStreamWriter(OutputStream out, CharsetEncoder enc) 
        
       
       
        
         public String getEncoding() 
        
       
       
        
         public void write(int c) throws IOException 
        
       
       
        
         public void write(char cbuf[], int off, int len) throws IOException 
        
       
       
        
         public void write(String str) throws IOException 
        
       
       
        
         public void write(String str, int off, int len) throws IOException 
        
       
       
        
         public void flush() throws IOException 
        
       
       
        
         public void close() throws IOException

      
       Пример использования  OutputStreamWriter/InputStreamReader 
      
     
      
       
        
         try{ //  Внешний блок try   try{ //  Создания потока для записи данных   or=new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(&quot;out.txt&quot;)),&quot;KOI8-R&quot;);   or.write(s);   }finally{   if(or!=null)   or.close();   }

      
       Пример использования  (продолжение) 
      
     
      
       
        
         try{ //  Создание потока для чтения данных   ir=new InputStreamReader(new BufferedInputStream(new FileInputStream(&quot;out.txt&quot;)),&quot;KOI8-R&quot;);   char[] b=new char[1024];   int i=0;   StringBuilder sb=new StringBuilder();   while((i=ir.read(b))!=-1)   {   sb.append(b, 0, i);   }   System.out.println(&quot;Result: &quot;+sb.toString());   }finally{   if(ir!=null)   ir.close();   }   }catch(Exception e) //  Перехват для внешнего try   {   System.out.println(e);   }

      
       FileReader 
      
     
      
       
        
         class FileReader extends InputStreamReader 
        
       
       
        
         public FileReader(String fileName) throws FileNotFoundException 
        
       
       
        
         public FileReader(File file) throws FileNotFoundException 
        
       
       
        
         public FileReader(FileDescriptor fd)

      
       FileWriter 
      
     
      
       
        
         class FileWriter extends OutputStreamWriter 
        
       
       
        
         public FileWriter(String fileName) throws IOException 
        
       
       
        
         public FileWriter(String fileName, boolean append) throws IOException 
        
       
       
        
         public FileWriter(File file) throws IOException 
        
       
       
        
         public FileWriter(File file, boolean append) throws IOException 
        
       
       
        
         public FileWriter(FileDescriptor fd)

      
       Пример использования  FileReader и FileWriter 
      
     
      
       
        
         try{  //  Внешний блок try   try{ //  Создание файла   fw=new FileWriter(&quot;out.txt&quot;);  fw.write(s); 
        
       
       
        
         }finally{ 
        
       
       
        
         if(fw!=null) 
        
       
       
        
         fw.close(); 
        
       
       
        
         }

      
       Пример использования (продолжение) 
      
     
      
       
        
         try{ 
        
       
       
        
         fr=new FileReader(&quot;out.txt&quot;); 
        
       
       
        
         char[] b=new char[1024]; 
        
       
       
        
         int i=0; 
        
       
       
        
         StringBuilder sb=new StringBuilder(); 
        
       
       
        
         while((i=fr.read(b))!=-1) 
        
       
       
        
         { 
        
       
       
        
         sb.append(b, 0, i); 
        
       
       
        
         } 
        
       
       
        
         System.out.println(sb.toString()); 
        
       
       
        
         }finally{ 
        
       
       
        
         if(fr!=null) 
        
       
       
        
         fr.close(); 
        
       
       
        
         } 
        
       
       
        
         }catch(Exception e) 
        
       
       
        
         { 
        
       
       
        
         System.out.println(e); 
        
       
       
        
         }

      
       BufferedReader 
      
     
      
       
        
         class BufferedReader extends Reader 
        
       
       
        
         public BufferedReader(Reader in, int sz) 
        
       
       
        
         public BufferedReader(Reader in) 
        
       
       
        
         public int read() throws IOException 
        
       
       
        
         public int read(char cbuf[], int off, int len) throws IOException 
        
       
       
        
         String readLine(boolean ignoreLF) throws IOException 
        
       
       
        
         public String readLine() throws IOException 
        
       
       
        
         public long skip(long n) throws IOException 
        
       
       
        
         public boolean ready() throws IOException 
        
       
       
        
         public boolean markSupported() 
        
       
       
        
         public void mark(int readAheadLimit) throws IOException 
        
       
       
        
         public void reset() throws IOException 
        
       
       
        
         public void close() throws IOException

      
       BufferedWriter 
      
     
      
       
        
         class BufferedWriter extends Writer 
        
       
       
        
         public BufferedWriter(Writer out) 
        
       
       
        
         public BufferedWriter(Writer out, int sz) 
        
       
       
        
         public void write(int c) throws IOException 
        
       
       
        
         public void write(char cbuf[], int off, int len) throws IOException 
        
       
       
        
         public void write(String s, int off, int len) throws IOException 
        
       
       
        
         public void newLine() throws IOException 
        
       
       
        
         public void flush() throws IOException 
        
       
       
        
         public void close() throws IOException

      
       Пример использования   BufferedReader/BufferedWriter 
      
     
      
       
        
         try{ //  Внешний блок try   try{ //  Создание потока для записи   bw=new BufferedWriter(new FileWriter(&quot;out.txt&quot;));   bw.write(s);    }finally{   if(bw!=null)   bw.close();   }   try{ //  Создание потока для чтения   br=new BufferedReader(new FileReader(&quot;out.txt&quot;));   String s1=br.readLine();   System.out.println(s1);   }finally{   if(br!=null)   br.close();   }   }catch(Exception e) //  Обработка исключений для внешнего try   {   System.out.println(e);   }

      
       DataInputStream 
      
     
      
       
        
         class DataInputStream extends FilterInputStream implements DataInput 
        
       
       
        
         public DataInputStream(InputStream in) 
        
       
       
        
         void readFully(byte b[]) throws IOException 
        
       
       
        
         void readFully(byte b[], int off, int len) throws IOException 
        
       
       
        
         int skipBytes(int n) throws IOException 
        
       
       
        
         boolean readBoolean() throws IOException 
        
       
       
        
         byte readByte() throws IOException 
        
       
       
        
         int readUnsignedByte() throws IOException 
        
       
       
        
         short readShort() throws IOException 
        
       
       
        
         int readUnsignedShort() throws IOException 
        
       
       
        
         char readChar() throws IOException 
        
       
       
        
         int readInt() throws IOException 
        
       
       
        
         long readLong() throws IOException 
        
       
       
        
         float readFloat() throws IOException 
        
       
       
        
         double readDouble() throws IOException 
        
       
       
        
         String readLine() throws IOException

      
       DataOutputStream 
      
     
      
       
        
         class DataOutputStream extends FilterOutputStream implements DataOutput 
        
       
       
        
         public DataOutputStream(OutputStream out) 
        
       
       
        
         void write(int b) throws IOException 
        
       
       
        
         void write(byte b[]) throws IOException 
        
       
       
        
         void write(byte b[], int off, int len) throws IOException 
        
       
       
        
         void writeBoolean(boolean v) throws IOException 
        
       
       
        
         void writeByte(int v) throws IOException 
        
       
       
        
         void writeShort(int v) throws IOException 
        
       
       
        
         void writeChar(int v) throws IOException 
        
       
       
        
         void writeInt(int v) throws IOException 
        
       
       
        
         void writeLong(long v) throws IOException 
        
       
       
        
         void writeFloat(float v) throws IOException 
        
       
       
        
         void writeDouble(double v) throws IOException 
        
       
       
        
         void writeBytes(String s) throws IOException 
        
       
       
        
         void writeChars(String s) throws IOException

      
       Пример использования DataInputStream/DataOutputStream 
      
     
      
       
        
         int i=10;   char c='a';   boolean b=true;   float f=10.6f;   String s=&quot;Hello&quot;;   try{   try{   dout=new DataOutputStream(new FileOutputStream(&quot;out2.txt&quot;));   dout.writeInt(i);   dout.writeChar(c);   dout.writeBoolean(b);   dout.writeFloat(f);   dout.writeUTF(s);   }finally{   if(dout!=null)   dout.close();   }

      
       Пример использования (продолжение) 
      
     
      
       
        
         try{   di=new DataInputStream(new FileInputStream(&quot;out2.txt&quot;));   int j=di.readInt();   char c1=di.readChar();   boolean b1=di.readBoolean();   float f1=di.readFloat();   String s1=di.readUTF();   System.out.println(&quot;Int: &quot;+j+&quot; char: &quot;+c1+&quot; bool: &quot;+b1+&quot; float: &quot;+f1+&quot; Str: &quot;+s1);   }finally{   if(di!=null)   di.close();   }  }catch(Exception e)   {   System.out.println(e);   }

      
       ObjectInputStream 
      
     
      
       
        
         class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants 
        
       
       
        
         public ObjectInputStream(InputStream in) throws IOException 
        
       
       
        
         public final Object readObject()  throws IOException, ClassNotFoundException

      
       ObjectOutputStream 
      
     
      
       
        
         class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants 
        
       
       
        
         public ObjectOutputStream(OutputStream out) throws IOException 
        
       
       
        
         public final void writeObject(Object obj) throws IOException

      
       Пример использования ObjectInputStream/ObjectOutputStream 
      
     
      
       
        
         TestClass tc=new TestClass(10,&quot;Hello, world&quot;);   System.out.println(tc);   try{   try{   oo=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(&quot;out3.txt&quot;)));   oo.writeObject(tc);   }finally{   if(oo!=null)  oo.close();   }   try{   oi=new ObjectInputStream(new BufferedInputStream(new FileInputStream(&quot;out3.txt&quot;)));   TestClass ttt=(TestClass)oi.readObject();   System.out.println(ttt);   }finally{   if(oi!=null)  oi.close();   }   }catch(Exception e){ System.out.println(e); }

      
       Конец 
      
     
      
       Вопросы 
       e-mail: a.bovanenko@gmail.com

More Related Content

PPT
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثامنة
PDF
Java I/o streams
PPS
Files & IO in Java
PPTX
PDF
Executable Bloat - How it happens and how we can fight it
PPT
Introduction to Python
PDF
Python Foundation – A programmer's introduction to Python concepts & style
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثامنة
Java I/o streams
Files & IO in Java
Executable Bloat - How it happens and how we can fight it
Introduction to Python
Python Foundation – A programmer's introduction to Python concepts & style
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...

What's hot (12)

PPTX
Introduction to python
ODP
Dynamic Python
PDF
File handling & regular expressions in python programming
PPT
Linux basics
PDF
What is Python?
PPT
Unit5 C
PPTX
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
PPTX
Learn Python The Hard Way Presentation
PDF
Python Tutorial
PDF
Introduction to python 3
PPT
Python ppt
ODP
Introduction to programming with python
Introduction to python
Dynamic Python
File handling & regular expressions in python programming
Linux basics
What is Python?
Unit5 C
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Learn Python The Hard Way Presentation
Python Tutorial
Introduction to python 3
Python ppt
Introduction to programming with python
Ad

Viewers also liked (6)

ODP
Perl. Anonymous arrays, hashes, subroutines. Closures
ODP
Regular Expressions
PPT
Конвертация строковых данных в числовые
ODP
ZIP, GZIP Streams in java
PDF
File. Java
ODP
Perl. Anonymous arrays, hashes, subroutines. Closures
Regular Expressions
Конвертация строковых данных в числовые
ZIP, GZIP Streams in java
File. Java
Ad

Similar to Java IO. Streams (20)

PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
PDF
26 io -ii file handling
PDF
Java - File Input Output Concepts
PPT
Itp 120 Chapt 19 2009 Binary Input & Output
PPTX
IO Programming.pptx all informatiyon ppt
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
PDF
What is java input and output stream?
PDF
What is java input and output stream?
PPTX
Input output files in java
PPTX
Basics of file handling
PPTX
basics of file handling
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
PPTX
Input/Output Exploring java.io
PPTX
Files and streams In Java
PPT
Io Streams
PPTX
Java program file I/O
PPTX
Chapter 10.3
PPTX
Understanding java streams
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
26 io -ii file handling
Java - File Input Output Concepts
Itp 120 Chapt 19 2009 Binary Input & Output
IO Programming.pptx all informatiyon ppt
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
What is java input and output stream?
What is java input and output stream?
Input output files in java
Basics of file handling
basics of file handling
chapter 2(IO and stream)/chapter 2, IO and stream
Input/Output Exploring java.io
Files and streams In Java
Io Streams
Java program file I/O
Chapter 10.3
Understanding java streams

More from Alexey Bovanenko (20)

PDF
Python sqlite3
PDF
Python. re
PDF
python dict
PDF
Python. Строки
PDF
Python. Введение
PPT
ODP
PPT
Обработка символов в языке C
ODP
PPTX
Javascript functions
PPTX
Javascript String object
PDF
Конструктор копирования
PDF
Tempale Intro
PDF
transaction. php
PDF
cookie. support by php
PDF
php sessions
ODP
Classes: Number, String, StringBuffer, StringBuilder
ODP
Объект Logger
ODP
Исключительные ситуации
ODP
Drag And Drop Windows Forms
Python sqlite3
Python. re
python dict
Python. Строки
Python. Введение
Обработка символов в языке C
Javascript functions
Javascript String object
Конструктор копирования
Tempale Intro
transaction. php
cookie. support by php
php sessions
Classes: Number, String, StringBuffer, StringBuilder
Объект Logger
Исключительные ситуации
Drag And Drop Windows Forms

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
master seminar digital applications in india
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Trump Administration's workforce development strategy
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Lesson notes of climatology university.
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
LDMMIA Reiki Yoga Finals Review Spring Summer
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Microbial diseases, their pathogenesis and prophylaxis
master seminar digital applications in india
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Complications of Minimal Access Surgery at WLH
Final Presentation General Medicine 03-08-2024.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
Trump Administration's workforce development strategy
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Yogi Goddess Pres Conference Studio Updates
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Lesson notes of climatology university.

Java IO. Streams

  • 1. Язык Java Потоки java.io Алексей Бованенко
  • 2. Введение Понятие потоков Поток представляет собой набор данных, связанный с источником (поток ввода), либо приемником (поток вывода) Источник или приемник Файлы на диске Устройства Другие программы Буфер в памяти Потоки могут содержать данные различных типов Примитивные типы Символы Объектные потоки
  • 3. Потоки в java.io В java.io определены следующие потоки InputStream / OutputStream FileInputStream / FileOutputStream BufferedInputStream / BufferedOutputStream InputStreamReader / OutputStreamWriter FileReader / FileWriter BufferedReader / BufferedWriter StringReader / StringWriter DataInputStream / DataOutputStream ObjectInputStream / ObjectOutputStream
  • 4. FileInputStream class FileInputStream extends InputStream public FileInputStream(String name) throws FileNotFoundException public FileInputStream(File file) throws FileNotFoundException public FileInputStream(FileDescriptor fdObj) public native int read() throws IOException private native int readBytes(byte b[], int off, int len) throws IOException public int read(byte b[]) throws IOException public int read(byte b[], int off, int len) throws IOException public native long skip(long n) throws IOException public native int available() throws IOException public void close() throws IOException public FileChannel getChannel() public boolean markSupported() public synchronized void reset() throws IOException public synchronized void mark(int readlimit)
  • 5. FileOutputStream class FileOutputStream extends OutputStream public FileOutputStream(String name) throws FileNotFoundException public FileOutputStream(String name, boolean append) throws FileNotFoundException public FileOutputStream(File file) throws FileNotFoundException public FileOutputStream(File file, boolean append) throws FileNotFoundException public FileOutputStream(FileDescriptor fdObj) public native void write(int b) throws IOException public void write(byte b[]) throws IOException public void write(byte b[], int off, int len) throws IOException public void close() throws IOException public void flush() throws IOException
  • 6. Пример использования (использование методов read() и write(int)) try{ // Внешний блок try try{ // Создание потока вывода fo=new FileOutputStream(&quot;out.txt&quot;); int l=s.length(); int i=0; while(i<l) { fo.write(s.codePointAt(i++)); } }finally{ if(fo!=null) fo.close(); }
  • 7. Пример (продолжение) try{ // Создание входного потока fi=new FileInputStream(&quot;out.txt&quot;); int i=0; StringBuilder sb=new StringBuilder(); while((i=fi.read())!=-1) { sb.append(Character.toChars(i)); } System.out.println(&quot;Received from file: &quot;+sb.toString()); }finally{ if(fi!=null) fi.close(); } }catch(FileNotFoundException e) // Перехват для внешнего try { System.out.println(e); }catch(IOException e) // Перехват для внешнего try { System.out.println(e); }
  • 8. Пример использования (использование методов read(byte[]) и write(byte[])) try{ // Внешний блок try try{ // Создание потока вывода fo=new FileOutputStream(&quot;out.txt&quot;); int l=s.length(); int i=0; byte[] b=s.getBytes(); fo.write(b); }finally{ if(fo!=null) fo.close(); }
  • 9. Пример (продолжение) try{ // Создание входного потока fi=new FileInputStream(&quot;out.txt&quot;); int i=fi.available(); byte[] b=new byte[i]; fi.read(b); String s1=new String(b); System.out.println(&quot;Received from file: &quot;+s1); }finally{ if(fi!=null) fi.close(); } }catch(FileNotFoundException e) // Перехват для внешнего try { System.out.println(e); }catch(IOException e) // Перехват для внешнего try { System.out.println(e); }
  • 10. Пример использования (использование методов read(byte[], int, int) и write(byte[], int , int)) try{ // Внешний блок try try{ // Создание потока вывода fo=new FileOutputStream(&quot;out.txt&quot;); int l=s.length(); int i=0; byte[] b=s.getBytes(); fo.write(b,0,b.length); }finally{ if(fo!=null) fo.close(); }
  • 11. Пример (продолжение) try{ // Создание входного потока fi=new FileInputStream(&quot;out.txt&quot;); int i=fi.available(); byte[] b=new byte[i]; fi.read(b,0,i); String s1=new String(b); System.out.println(&quot;Received from file: &quot;+s1); }finally{ if(fi!=null) fi.close(); } }catch(FileNotFoundException e) // Перехват для внешнего try { System.out.println(e); }catch(IOException e) // Перехват для внешнего try { System.out.println(e); }
  • 12. BufferedInputStream class BufferedInputStream extends FilterInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int size) public synchronized int read() throws IOException public synchronized int read(byte b[], int off, int len) throws IOException public synchronized long skip(long n) throws IOException public synchronized int available() throws IOException public synchronized void mark(int readlimit) public synchronized void reset() throws IOException public boolean markSupported() public void close() throws IOException
  • 13. BufferedOutputStream class BufferedOutputStream extends FilterOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStream out, int size) public synchronized void write(int b) throws IOException public synchronized void write(byte b[], int off, int len) throws IOException public synchronized void flush() throws IOException
  • 14. Пример использования BufferedInputStream/BufferedOutputStream try{ // Внешний блок try try{ // Создание потока для записи файла bo=new BufferedOutputStream(new FileOutputStream(&quot;out.txt&quot;)); byte[] b=new byte[s.length()]; b=s.getBytes(); bo.write(b,0,b.length); }finally{ if(bo!=null) bo.close(); }
  • 15. Пример использования (продолжение) try{ // Создание потока для чтения bi=new BufferedInputStream(new FileInputStream(&quot;out.txt&quot;)); int i=bi.available(); byte[] b=new byte[i]; bi.mark(i); bi.read(b, 0, i); bi.reset(); String s1=new String(b); bi.read(b, 0, i); String s2=new String(b); System.out.println(s1+&quot; &quot;+s2); }finally{ if(bi!=null) bi.close(); } }catch(Exception e){ // Перехват для внешнего try System.out.println(e); }
  • 16. InputStreamReader public class InputStreamReader extends Reader public InputStreamReader(InputStream in) public InputStreamReader(InputStream in, String charsetName) public InputStreamReader(InputStream in, Charset cs) public InputStreamReader(InputStream in, CharsetDecoder dec) public String getEncoding() public int read() throws IOException public int read(char cbuf[]) throws IOException public int read(char cbuf[], int offset, int length) throws IOException public boolean ready() throws IOException public void close() throws IOException
  • 17. OutputStreamWriter class OutputStreamWriter extends Writer public OutputStreamWriter(OutputStream out, String charsetName) throws UnsupportedEncodingException public OutputStreamWriter(OutputStream out) public OutputStreamWriter(OutputStream out, Charset cs) public OutputStreamWriter(OutputStream out, CharsetEncoder enc) public String getEncoding() public void write(int c) throws IOException public void write(char cbuf[], int off, int len) throws IOException public void write(String str) throws IOException public void write(String str, int off, int len) throws IOException public void flush() throws IOException public void close() throws IOException
  • 18. Пример использования OutputStreamWriter/InputStreamReader try{ // Внешний блок try try{ // Создания потока для записи данных or=new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(&quot;out.txt&quot;)),&quot;KOI8-R&quot;); or.write(s); }finally{ if(or!=null) or.close(); }
  • 19. Пример использования (продолжение) try{ // Создание потока для чтения данных ir=new InputStreamReader(new BufferedInputStream(new FileInputStream(&quot;out.txt&quot;)),&quot;KOI8-R&quot;); char[] b=new char[1024]; int i=0; StringBuilder sb=new StringBuilder(); while((i=ir.read(b))!=-1) { sb.append(b, 0, i); } System.out.println(&quot;Result: &quot;+sb.toString()); }finally{ if(ir!=null) ir.close(); } }catch(Exception e) // Перехват для внешнего try { System.out.println(e); }
  • 20. FileReader class FileReader extends InputStreamReader public FileReader(String fileName) throws FileNotFoundException public FileReader(File file) throws FileNotFoundException public FileReader(FileDescriptor fd)
  • 21. FileWriter class FileWriter extends OutputStreamWriter public FileWriter(String fileName) throws IOException public FileWriter(String fileName, boolean append) throws IOException public FileWriter(File file) throws IOException public FileWriter(File file, boolean append) throws IOException public FileWriter(FileDescriptor fd)
  • 22. Пример использования FileReader и FileWriter try{ // Внешний блок try try{ // Создание файла fw=new FileWriter(&quot;out.txt&quot;); fw.write(s); }finally{ if(fw!=null) fw.close(); }
  • 23. Пример использования (продолжение) try{ fr=new FileReader(&quot;out.txt&quot;); char[] b=new char[1024]; int i=0; StringBuilder sb=new StringBuilder(); while((i=fr.read(b))!=-1) { sb.append(b, 0, i); } System.out.println(sb.toString()); }finally{ if(fr!=null) fr.close(); } }catch(Exception e) { System.out.println(e); }
  • 24. BufferedReader class BufferedReader extends Reader public BufferedReader(Reader in, int sz) public BufferedReader(Reader in) public int read() throws IOException public int read(char cbuf[], int off, int len) throws IOException String readLine(boolean ignoreLF) throws IOException public String readLine() throws IOException public long skip(long n) throws IOException public boolean ready() throws IOException public boolean markSupported() public void mark(int readAheadLimit) throws IOException public void reset() throws IOException public void close() throws IOException
  • 25. BufferedWriter class BufferedWriter extends Writer public BufferedWriter(Writer out) public BufferedWriter(Writer out, int sz) public void write(int c) throws IOException public void write(char cbuf[], int off, int len) throws IOException public void write(String s, int off, int len) throws IOException public void newLine() throws IOException public void flush() throws IOException public void close() throws IOException
  • 26. Пример использования BufferedReader/BufferedWriter try{ // Внешний блок try try{ // Создание потока для записи bw=new BufferedWriter(new FileWriter(&quot;out.txt&quot;)); bw.write(s); }finally{ if(bw!=null) bw.close(); } try{ // Создание потока для чтения br=new BufferedReader(new FileReader(&quot;out.txt&quot;)); String s1=br.readLine(); System.out.println(s1); }finally{ if(br!=null) br.close(); } }catch(Exception e) // Обработка исключений для внешнего try { System.out.println(e); }
  • 27. DataInputStream class DataInputStream extends FilterInputStream implements DataInput public DataInputStream(InputStream in) void readFully(byte b[]) throws IOException void readFully(byte b[], int off, int len) throws IOException int skipBytes(int n) throws IOException boolean readBoolean() throws IOException byte readByte() throws IOException int readUnsignedByte() throws IOException short readShort() throws IOException int readUnsignedShort() throws IOException char readChar() throws IOException int readInt() throws IOException long readLong() throws IOException float readFloat() throws IOException double readDouble() throws IOException String readLine() throws IOException
  • 28. DataOutputStream class DataOutputStream extends FilterOutputStream implements DataOutput public DataOutputStream(OutputStream out) void write(int b) throws IOException void write(byte b[]) throws IOException void write(byte b[], int off, int len) throws IOException void writeBoolean(boolean v) throws IOException void writeByte(int v) throws IOException void writeShort(int v) throws IOException void writeChar(int v) throws IOException void writeInt(int v) throws IOException void writeLong(long v) throws IOException void writeFloat(float v) throws IOException void writeDouble(double v) throws IOException void writeBytes(String s) throws IOException void writeChars(String s) throws IOException
  • 29. Пример использования DataInputStream/DataOutputStream int i=10; char c='a'; boolean b=true; float f=10.6f; String s=&quot;Hello&quot;; try{ try{ dout=new DataOutputStream(new FileOutputStream(&quot;out2.txt&quot;)); dout.writeInt(i); dout.writeChar(c); dout.writeBoolean(b); dout.writeFloat(f); dout.writeUTF(s); }finally{ if(dout!=null) dout.close(); }
  • 30. Пример использования (продолжение) try{ di=new DataInputStream(new FileInputStream(&quot;out2.txt&quot;)); int j=di.readInt(); char c1=di.readChar(); boolean b1=di.readBoolean(); float f1=di.readFloat(); String s1=di.readUTF(); System.out.println(&quot;Int: &quot;+j+&quot; char: &quot;+c1+&quot; bool: &quot;+b1+&quot; float: &quot;+f1+&quot; Str: &quot;+s1); }finally{ if(di!=null) di.close(); } }catch(Exception e) { System.out.println(e); }
  • 31. ObjectInputStream class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants public ObjectInputStream(InputStream in) throws IOException public final Object readObject() throws IOException, ClassNotFoundException
  • 32. ObjectOutputStream class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants public ObjectOutputStream(OutputStream out) throws IOException public final void writeObject(Object obj) throws IOException
  • 33. Пример использования ObjectInputStream/ObjectOutputStream TestClass tc=new TestClass(10,&quot;Hello, world&quot;); System.out.println(tc); try{ try{ oo=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(&quot;out3.txt&quot;))); oo.writeObject(tc); }finally{ if(oo!=null) oo.close(); } try{ oi=new ObjectInputStream(new BufferedInputStream(new FileInputStream(&quot;out3.txt&quot;))); TestClass ttt=(TestClass)oi.readObject(); System.out.println(ttt); }finally{ if(oi!=null) oi.close(); } }catch(Exception e){ System.out.println(e); }
  • 34. Конец Вопросы e-mail: a.bovanenko@gmail.com