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

What's hot (12)

Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
MaheshPandit16
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
Chui-Wen Chiu
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
Srinivas Narasegouda
 
Linux basics
Linux basicsLinux basics
Linux basics
sirmanohar
 
What is Python?
What is Python?What is Python?
What is Python?
wesley chun
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
AkramWaseem
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3
Youhei Sakurai
 
Python ppt
Python pptPython ppt
Python ppt
Rohit Verma
 
Introduction to programming with python
Introduction to programming with pythonIntroduction to programming with python
Introduction to programming with python
Porimol Chandro
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
MaheshPandit16
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
Srinivas Narasegouda
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3
Youhei Sakurai
 
Introduction to programming with python
Introduction to programming with pythonIntroduction to programming with python
Introduction to programming with python
Porimol Chandro
 

Viewers also liked (6)

Perl. Anonymous arrays, hashes, subroutines. Closures
Perl. Anonymous arrays, hashes, subroutines. ClosuresPerl. Anonymous arrays, hashes, subroutines. Closures
Perl. Anonymous arrays, hashes, subroutines. Closures
Alexey Bovanenko
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
Alexey Bovanenko
 
Конвертация строковых данных в числовые
Конвертация строковых данных в числовыеКонвертация строковых данных в числовые
Конвертация строковых данных в числовые
Alexey Bovanenko
 
ZIP, GZIP Streams in java
ZIP, GZIP Streams in javaZIP, GZIP Streams in java
ZIP, GZIP Streams in java
Alexey Bovanenko
 
File. Java
File. JavaFile. Java
File. Java
Alexey Bovanenko
 
Perl. Anonymous arrays, hashes, subroutines. Closures
Perl. Anonymous arrays, hashes, subroutines. ClosuresPerl. Anonymous arrays, hashes, subroutines. Closures
Perl. Anonymous arrays, hashes, subroutines. Closures
Alexey Bovanenko
 
Конвертация строковых данных в числовые
Конвертация строковых данных в числовыеКонвертация строковых данных в числовые
Конвертация строковых данных в числовые
Alexey Bovanenko
 

Similar to Java IO. Streams (20)

11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
Ravindra Rathore
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdfMonhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
kanchanmahajan23
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
kanchanmahajan23
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
Rajan Shah
 
Io Streams
Io StreamsIo Streams
Io Streams
phanleson
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
Nem Sothea
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
JAVA
JAVAJAVA
JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdfMonhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
kanchanmahajan23
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
kanchanmahajan23
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
Rajan Shah
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
Nem Sothea
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 

More from Alexey Bovanenko (20)

Python sqlite3
Python sqlite3Python sqlite3
Python sqlite3
Alexey Bovanenko
 
Python. re
Python. rePython. re
Python. re
Alexey Bovanenko
 
python dict
python dictpython dict
python dict
Alexey Bovanenko
 
Python. Строки
Python. СтрокиPython. Строки
Python. Строки
Alexey Bovanenko
 
Python. Введение
Python. ВведениеPython. Введение
Python. Введение
Alexey Bovanenko
 
Обработка символов в языке C
Обработка символов в языке CОбработка символов в языке C
Обработка символов в языке C
Alexey Bovanenko
 
Javascript String object
Javascript String objectJavascript String object
Javascript String object
Alexey Bovanenko
 
Конструктор копирования
Конструктор копированияКонструктор копирования
Конструктор копирования
Alexey Bovanenko
 
Tempale Intro
Tempale IntroTempale Intro
Tempale Intro
Alexey Bovanenko
 
transaction. php
transaction. phptransaction. php
transaction. php
Alexey Bovanenko
 
cookie. support by php
cookie. support by phpcookie. support by php
cookie. support by php
Alexey Bovanenko
 
php sessions
php sessionsphp sessions
php sessions
Alexey Bovanenko
 
Classes: Number, String, StringBuffer, StringBuilder
Classes: Number, String, StringBuffer, StringBuilderClasses: Number, String, StringBuffer, StringBuilder
Classes: Number, String, StringBuffer, StringBuilder
Alexey Bovanenko
 
Исключительные ситуации
Исключительные ситуацииИсключительные ситуации
Исключительные ситуации
Alexey Bovanenko
 
Drag And Drop Windows Forms
Drag And Drop Windows FormsDrag And Drop Windows Forms
Drag And Drop Windows Forms
Alexey Bovanenko
 

Recently uploaded (20)

U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Look Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History EverywhereLook Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History Everywhere
History of Stoke Newington
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Bipolar Junction Transistors (BJTs): Basics, Construction & Configurations
Bipolar Junction Transistors (BJTs): Basics, Construction & ConfigurationsBipolar Junction Transistors (BJTs): Basics, Construction & Configurations
Bipolar Junction Transistors (BJTs): Basics, Construction & Configurations
GS Virdi
 
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdfGENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
Quiz Club of PSG College of Arts & Science
 
The History of Kashmir Lohar Dynasty NEP.ppt
The History of Kashmir Lohar Dynasty NEP.pptThe History of Kashmir Lohar Dynasty NEP.ppt
The History of Kashmir Lohar Dynasty NEP.ppt
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
PUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for HealthPUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for Health
JonathanHallett4
 
libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2
LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2
LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2
LDM & Mia eStudios
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Look Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History EverywhereLook Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History Everywhere
History of Stoke Newington
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Bipolar Junction Transistors (BJTs): Basics, Construction & Configurations
Bipolar Junction Transistors (BJTs): Basics, Construction & ConfigurationsBipolar Junction Transistors (BJTs): Basics, Construction & Configurations
Bipolar Junction Transistors (BJTs): Basics, Construction & Configurations
GS Virdi
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
PUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for HealthPUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for Health
JonathanHallett4
 
libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2
LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2
LDMMIA Reiki Yoga S6 Free Workshop Money Pt 2
LDM & Mia eStudios
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 

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
  翻译: