Потоки
Иерархия классов байтовых потоков вывода
Класс OutputStream
Класс FileOutputStream
Запись в файл по одному байту
Запись в файл массива байтов
Запись в файл
Запись строки в файл
Класс FilterOutputStream
Класс BufferedOutputStream
Класс BufferedOutputStream
Опустошение буфера
Опустошение буфера
Производительность буферизованного вывода
Производительность небуферизованного вывода
Иерархия классов байтовых потоков ввода
Класс InputStream
Класс FileInputStream
Чтение из файла по одному байту
Чтение в массив байтов
Чтение строки из файла
Класс FilterInputStream
Класс BufferedInputStream
Производительность буферизованного ввода
Производительность небуферизованного ввода
946.22K
Категория: ПрограммированиеПрограммирование

Ввод - вывод. Байтовые потоки

1.

2.

V. Ввод - вывод
2. Байтовые потоки
2

3. Потоки

Объект из которого можно прочитать последовательность байтов называется
байтовый
поток
ввода.
Объект
в
который
можно
записать
последовательность байтов называется байтовый поток вывода. Классы
байтовых
потоков
ввода
являются
подклассами
абстрактного
класса InputStream, потоков вывода – подклассами абстрактного класса
OutputStream. Классы байтовых потоков находятся в пакете java.io.
3

4.

Потоки вывода
4

5. Иерархия классов байтовых потоков вывода

Шаблон Декоратор: Иерархия классов
байтовых
потоков
вывода
является
примером применения шаблона Декоратор.
5

6. Класс OutputStream

public
public abstract
abstract class
class OutputStream
OutputStream implements
implements Closeable,
Closeable, Flushable
Flushable
{{
public
public abstract
abstract void
void write(int
write(int b)
b)
public
public void
void write(byte
write(byte b[])
b[]) throws
throws IOException
IOException {{
write(b,
write(b, 0,
0, b.length);
b.length);
}}
public
public
if
if
}}
void
void write(byte
write(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException
IOException {{
(b
(b ==
== null)
null) {{
throw
throw new
new NullPointerException();
NullPointerException();
}} else
else if
if ((off
((off << 0)
0) ||
|| (off
(off >> b.length)
b.length) ||
|| (len
(len << 0)
0) ||
||
((off
((off ++ len)
len) >> b.length)
b.length) ||
|| ((off
((off ++ len)
len) << 0))
0)) {{
throw
new
IndexOutOfBoundsException();
throw new IndexOutOfBoundsException();
}} else
else if
if (len
(len ==
== 0)
0) {{
return;
return;
}}
for
for (int
(int ii == 00 ;; ii << len
len ;; i++)
i++) {{
write(b[off
write(b[off ++ i]);
i]);
}}
public
public void
void flush()
flush() throws
throws IOException
IOException {{
}}
}}
public
public void
void close()
close() throws
throws IOException
IOException {{
}}
C
A
Абстрактный класс OutputStream – базовый класс для потоков вывода. Для вывода одного байта в нём
объявлен абстрактный метод write. Конкретные классы потомки должны переопределять этот метод. Как
правило потомки переопределяют и другие методы write более эффективными реализациями. Класс содержит
пустые реализации методов close и flush. Метод close предназначен для закрытия потока после окончания
записи. Закрытие потока освобождает ограниченные системные ресурсы, а также освобождает буфер если он
используется. Метод flush предназначен для опустошения буфера если поток буферизованный.
6

7. Класс FileOutputStream

public
public class
class FileOutputStream
FileOutputStream extends
extends OutputStream
OutputStream
{{
public
public FileOutputStream(String
FileOutputStream(String name)
name) throws
throws FileNotFoundException
FileNotFoundException
public
FileOutputStream(String
name,
append
boolean)
public FileOutputStream(String name, append boolean) throws
throws FileNotFoundException
FileNotFoundException
public
public native
native void
void write(int
write(int b)
b) throws
throws IOException;
IOException;
private
private native
native void
void writeBytes(byte
writeBytes(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException;
IOException;
public
public void
void write(byte
write(byte b[])
b[]) throws
throws IOException
IOException {{
writeBytes(b,
writeBytes(b, 0,
0, b.length);
b.length);
}}
public
public void
void write(byte
write(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException
IOException {{
writeBytes(b,
writeBytes(b, off,
off, len);
len);
}}
}}
public
public void
void close()
close() throws
throws IOException
IOException
C
Класс FileOutputStream предназначен для записи последовательности байтов в файлы. Он
переопределяет методы write и метод close из класса OutputStream. Метод close закрывает поток и
освобождает файловый дескриптор. Конструктор позволяет задать имя файла для записи. Также можно
указать следует ли перезаписывать существующий файл или дописывать в него.
7

8. Запись в файл по одному байту

public
public class
class WriteByteDemo
WriteByteDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
FileOutputStream
FileOutputStream
int[]
int[] ints
ints == new
new
}}
}}
out
out == null;
null;
int[256];
int[256];
try
try {{
out
out == new
new FileOutputStream("I:\\FileIO\\
FileOutputStream("I:\\FileIO\\ bytesfile.dat");
bytesfile.dat");
for
for (int
(int ii == 0;
0; ii << 256;
256; i++)
i++) {{
ints[i]
ints[i] == i;
i;
out.write(i);
out.write(i);
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
finally {{
try
try {{
if
if (out
(out !=
!= null)
null)
out.close();
out.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
System.out.println(Arrays.toString(ints));
System.out.println(Arrays.toString(ints));
[0,
[0, 1,
1, 2,
2, 3,
3, 4,
4, 5,
5, ...
... ,125,
,125, 126,
126, 127,
127, 128,
128, 129,
129, 130,
130, 131,
131, ...
... ,250,
,250, 251,
251, 252,
252, 253,
253, 254,
254, 255]
255]
8

9. Запись в файл массива байтов

public
public class
class WriteBytesDemo
WriteBytesDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
FileOutputStream
FileOutputStream out
out == null;
null;
byte[]
bytes
=
new
byte[256];
byte[] bytes = new byte[256];
for
for (int
(int ii == 0;
0; ii << 256;
256; i++)
i++) {{
bytes[i]
bytes[i] == (byte)
(byte) i;
i;
}}
}}
}}
try
try {{
out
out == new
new FileOutputStream("I:\\FileIO\\
FileOutputStream("I:\\FileIO\\ bytesfile.dat");
bytesfile.dat");
out.write(bytes);
out.write(bytes);
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
{
finally {
try
try {{
if
if (out
(out !=
!= null)
null)
out.close();
out.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(bytes));
[0,
[0, 1,
1, 2,
2, 3,
3, 4,
4, 5,
5, ...
... ,125,
,125, 126,
126, 127,
127, -128,
-128, -127,
-127, -126,
-126, -125,
-125, ...
... ,, -5,
-5, -4,
-4, -3,
-3, -2,
-2, -1]
-1]
9

10. Запись в файл

10

11. Запись строки в файл

public
public class
class WriteStringDemo
WriteStringDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
String
String
byte[]
byte[]
source
source == "Hello
"Hello World!";
World!";
bytes
=
source.getBytes();
bytes = source.getBytes();
FileOutputStream
FileOutputStream out
out == null;
null;
}}
}}
try
try {{
out
out == new
new FileOutputStream("I:\\FileIO\\stringfile.dat");
FileOutputStream("I:\\FileIO\\stringfile.dat");
out.write(bytes);
out.write(bytes);
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
finally {{
try
try {{
if
if (out
(out !=
!= null)
null)
out.close();
out.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(bytes));
[72,
[72, 101,
101, 108,
108, 108,
108, 111,
111, 32,
32, 87,
87, 111,
111, 114,
114, 108,
108, 100,
100, 33]
33]
Hello
World!
Hello World!
11

12.

Буферизованный вывод
12

13. Класс FilterOutputStream

public
public class
class FilterOutputStream
FilterOutputStream extends
extends OutputStream
OutputStream {{
protected
protected OutputStream
OutputStream out;
out;
public
public FilterOutputStream(OutputStream
FilterOutputStream(OutputStream out)
out) {{
this.out
this.out == out;
out;
}}
public
public void
void write(int
write(int b)
b) throws
throws IOException
IOException {{
out.write(b);
out.write(b);
}}
public
public void
void write(byte
write(byte b[])
b[]) throws
throws IOException
IOException {{
write(b,
0,
b.length);
write(b, 0, b.length);
}}
public
public void
void write(byte
write(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException
IOException {{
if
((off
|
len
|
(b.length
(len
+
off))
|
(off
+
if ((off | len | (b.length - (len + off)) | (off + len))
len)) << 0)
0)
throw
new
IndexOutOfBoundsException();
throw new IndexOutOfBoundsException();
for
for (int
(int ii == 00 ;; ii << len
len ;; i++)
i++) {{
write(b[off
write(b[off ++ i]);
i]);
}}
}}
public
public void
void flush()
flush() throws
throws IOException
IOException {{
out.flush();
out.flush();
}}
}}
public
public void
void close()
close() throws
throws IOException
IOException {{
try
try {{
flush();
flush();
}} catch
catch (IOException
(IOException ignored)
ignored) {{ }}
out.close();
out.close();
}}
C
Класс FilterOutputStream – базовый класс для всех фильтрующих потоков вывода. Эти классы оборачивают
существующий поток вывода который используется как сток данных возможно преобразуя данные или
предоставляя дополнительную функциональность. Класс FilterOutputStream просто переопределяет все методы
класса OutputStream версиями которые перенаправляют все запросы оборачиваемому потоку. Классы потомки
FilterOutputStream могут переопределять эти методы а также предоставлять дополнительные методы и поля.
13

14. Класс BufferedOutputStream

public
public class
class BufferedOutputStream
BufferedOutputStream extends
extends FilterOutputStream
FilterOutputStream {{
protected
protected byte
byte buf[];
buf[];
protected
protected int
int count;
count;
public
public BufferedOutputStream(OutputStream
BufferedOutputStream(OutputStream out)
out) {{
this(out,
this(out, 8192);
8192);
}}
public
public BufferedOutputStream(OutputStream
BufferedOutputStream(OutputStream out,
out, int
int size)
size) {{
super(out);
super(out);
if
if (size
(size <=
<= 0)
0) {{
throw
throw new
new IllegalArgumentException("Buffer
IllegalArgumentException("Buffer size
size <=
<= 0");
0");
}}
buf
buf == new
new byte[size];
byte[size];
}}
private
private void
void flushBuffer()
flushBuffer() throws
throws IOException
IOException {{
if
if (count
(count >> 0)
0) {{
out.write(buf,
out.write(buf, 0,
0, count);
count);
count
=
0;
count = 0;
}}
}}
}}
public
public synchronized
synchronized void
void flush()
flush() throws
throws IOException
IOException {{
flushBuffer();
flushBuffer();
out.flush();
out.flush();
}}
...
...
C
Класс BufferedOutputStream - реализует буферизованный поток вывода для повышения эффективности
вывода данных. В конструкторе необходимо задать оборачиваемый поток. Для хранения данных
используется массив byte размер которого можно задать в конструкторе. Метод flush переопределён
он выполняет опустошение буфера и вызов метода flush у оборачиваемого потока.
14

15. Класс BufferedOutputStream

public
public class
class BufferedOutputStream
BufferedOutputStream extends
extends FilterOutputStream
FilterOutputStream {{
...
...
public
public
if
if
}}
}}
synchronized
synchronized void
void write(int
write(int b)
b) throws
throws IOException
IOException {{
(count
(count >=
>= buf.length)
buf.length) {{
flushBuffer();
flushBuffer();
}}
buf[count++]
buf[count++] == (byte)b;
(byte)b;
public
public synchronized
synchronized void
void write(byte
write(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException
IOException {{
if
if (len
(len >=
>= buf.length)
buf.length) {{
flushBuffer();
flushBuffer();
out.write(b,
out.write(b, off,
off, len);
len);
return;
return;
}}
if
if (len
(len >> buf.length
buf.length -- count)
count) {{
flushBuffer();
flushBuffer();
}}
System.arraycopy(b,
System.arraycopy(b, off,
off, buf,
buf, count,
count, len);
len);
count
count +=
+= len;
len;
}}
C
При использовании буферизованного потока вывода данные могут накапливаться в буфере и
выводиться при наполнении буфера. Таким образом можно снизить количество операций записи в
оборачиваемый поток и повысить эффективность.
15

16. Опустошение буфера

public
public class
class WriteFlushDemo
WriteFlushDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
String
String source
source == "Hello
"Hello World!";
World!";
byte[]
byte[] bytes
bytes == source.getBytes();
source.getBytes();
BufferedOutputStream
BufferedOutputStream
BufferedOutputStream
BufferedOutputStream
out1
out1
out2
out2
==
==
null;
null;
null;
null;
try
try {{
out1
out1 == new
new BufferedOutputStream(new
BufferedOutputStream(new FileOutputStream("I:\\FileIO\\file1.dat"));
FileOutputStream("I:\\FileIO\\file1.dat"));
out2
out2 == new
new BufferedOutputStream(new
BufferedOutputStream(new FileOutputStream("I:\\FileIO\\file2.dat"));
FileOutputStream("I:\\FileIO\\file2.dat"));
out1.write(bytes);
out1.write(bytes);
out2.write(bytes);
out2.write(bytes);
}}
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
{
finally {
try
try {{
if
if (out1
(out1 !=
!= null)
null)
out1.close();
out1.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(bytes));
[72,
[72, 101,
101, 108,
108, 108,
108, 111,
111, 32,
32, 87,
87, 111,
111, 114,
114, 108,
108, 100,
100, 33]
33]
16

17. Опустошение буфера

17

18. Производительность буферизованного вывода

public
public class
class WriteBufPerform
WriteBufPerform {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
BufferedOutputStream
BufferedOutputStream outbuf
outbuf == null;
null;
FileOutputStream
FileOutputStream out
out == null;
null;
long
long time
time == System.currentTimeMillis();
System.currentTimeMillis();
try
{
try {
outbuf
outbuf == new
new BufferedOutputStream(new
BufferedOutputStream(new FileOutputStream("I:\\FileIO\\outbuf.dat"));
FileOutputStream("I:\\FileIO\\outbuf.dat"));
}}
}}
for
for (int
(int ii == 0;
0; ii << 10000000;
10000000; i++)
i++) {{
outbuf.write(65);
outbuf.write(65);
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
finally {{
try
try {{
if
if (outbuf
(outbuf !=
!= null)
null)
outbuf.close();
outbuf.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
time
time == System.currentTimeMillis()
System.currentTimeMillis() -- time;
time;
System.out.println("Buffered
System.out.println("Buffered output
output time:
time: "" ++ time);
time);
...
...
18

19. Производительность небуферизованного вывода

public
public class
class WriteBufPerform
WriteBufPerform {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
...
...
time
time ==
try
try {{
out
out
}}
}}
System.currentTimeMillis();
System.currentTimeMillis();
== new
new FileOutputStream("I:\\FileIO\\outnobuf.dat");
FileOutputStream("I:\\FileIO\\outnobuf.dat");
for
for (int
(int ii == 0;
0; ii << 10000000;
10000000; i++)
i++) {{
out.write(65);
out.write(65);
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
finally {{
try
try {{
if
if (out
(out !=
!= null)
null)
out.close();
out.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
time
time == System.currentTimeMillis()
System.currentTimeMillis() -- time;
time;
System.out.println("Non-buffered
System.out.println("Non-buffered output
output time:
time: "" ++ time);
time);
Buffered
Buffered output
output time:
time: 344
344
Non-buffered
Non-buffered output
output time:
time: 35766
35766
19

20.

Потоки ввода
20

21. Иерархия классов байтовых потоков ввода

Шаблон Декоратор: Иерархия классов
байтовых
потоков
вввода
является
примером применения шаблона Декоратор.
21

22. Класс InputStream

public
public abstract
abstract class
class InputStream
InputStream implements
implements Closeable
Closeable {{
public
public abstract
abstract int
int read()
read() throws
throws IOException;
IOException;
public
public int
int
return
return
}}
read(byte
read(byte b[])
b[]) throws
throws IOException
IOException {{
read(b,
read(b, 0,
0, b.length);
b.length);
public
public int
int read(byte
read(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException
IOException
}}
public
public void
void close()
close() throws
throws IOException
IOException {}
{}
C
A
Абстрактный класс InputStream – базовый класс для потоков ввода. Для чтения одного байта в нём
объявлен абстрактный метод read. Этот метод считывает один байт и возвращает его значение или -1 если
он сразу же встретил конец потока. По этой причине тип возвращаемого значения int, а не byte.
Конкретные классы потомки должны переопределять этот метод. Как правило потомки переопределяют и
другие методы read более эффективными реализациями. Другие методы read пытаются считать заданное
количество байтов в массив. Если предпринимается попытка считать 0 байтов методы вернут 0. В
противном случае возвращается количество считанных байтов или -1 если нельзя считать ни одного байта
из-за того что сразу был встречен конец потока.
22

23. Класс FileInputStream

public
public class
class FileInputStream
FileInputStream extends
extends InputStream
InputStream
{{
public
public FileInputStream(String
FileInputStream(String name)
name) throws
throws FileNotFoundException
FileNotFoundException {{
this(name
this(name !=
!= null
null ?? new
new File(name)
File(name) :: null);
null);
}}
public
public FileInputStream(File
FileInputStream(File file)
file)
public
public native
native int
int read()
read() throws
throws IOException;
IOException;
public
public int
int read(byte
read(byte b[])
b[]) throws
throws IOException
IOException {{
return
return readBytes(b,
readBytes(b, 0,
0, b.length);
b.length);
}}
public
public int
int read(byte
read(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException
IOException {{
return
return readBytes(b,
readBytes(b, off,
off, len);
len);
}}
private
private native
native int
int readBytes(byte
readBytes(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException;
IOException;
}}
public
public void
void close()
close() throws
throws IOException
IOException
C
Класс FileInputStream предназначен для чтения последовательности байтов
из файла. Он переопределяет методы read и метод close из класса
InputStream. Конструктор позволяет задать имя файла для чтения. Метод
close закрывает поток и освобождает файловый дескриптор.
23

24. Чтение из файла по одному байту

public
public class
class ReadByteDemo
ReadByteDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
FileInputStream
FileInputStream in
in == null;
null;
int[]
ints
=
new
int[256];
int[] ints = new int[256];
int
int temp;
temp;
try
try {{
in
in == new
new FileInputStream("I:\\FileIO\\bytesfile.dat");
FileInputStream("I:\\FileIO\\bytesfile.dat");
for
(int
i
for (int i == 0;
0; ii << 256;
256; i++)
i++) {{
temp
temp == in.read();
in.read();
if
if (temp
(temp ==
== -1)
-1)
break;
break;
ints[i]
ints[i] == temp;
temp;
}}
}}
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
{
finally {
try
try {{
if
if (in
(in !=
!= null)
null)
in.close();
in.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
System.out.println(Arrays.toString(ints));
System.out.println(Arrays.toString(ints));
[0,
[0, 1,
1, 2,
2, 3,
3, 4,
4, 5,
5, ...
... ,125,
,125, 126,
126, 127,
127, 128,
128, 129,
129, 130,
130, 131,
131, ...
... ,250,
,250, 251,
251, 252,
252, 253,
253, 254,
254, 255]
255]
24

25. Чтение в массив байтов

public
public class
class ReadBytesDemo
ReadBytesDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
FileInputStream
FileInputStream in
in
byte[]
bytes
=
new
byte[] bytes = new
}}
}}
== null;
null;
byte[256];
byte[256];
try
try {{
in
in == new
new FileInputStream("I:\\FileIO\\bytesfile.dat");
FileInputStream("I:\\FileIO\\bytesfile.dat");
in.read(bytes);
in.read(bytes);
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
finally {{
try
try {{
if
if (in
(in !=
!= null)
null)
in.close();
in.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(bytes));
[0,
[0, 1,
1, 2,
2, 3,
3, 4,
4, 5,
5, ...
... ,125,
,125, 126,
126, 127,
127, -128,
-128, -127,
-127, -126,
-126, -125,
-125, ...
... ,, -5,
-5, -4,
-4, -3,
-3, -2,
-2, -1]
-1]
25

26. Чтение строки из файла

public
public class
class ReadStringDemo
ReadStringDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
FileInputStream
FileInputStream in
in
byte[]
bytes
=
new
byte[] bytes = new
int
int nbytes
nbytes == 0;
0;
}}
}}
== null;
null;
byte[256];
byte[256];
try
try {{
in
in == new
new FileInputStream("I:\\FileIO\\stringfile.dat");
FileInputStream("I:\\FileIO\\stringfile.dat");
nbytes
=
in.read(bytes);
nbytes = in.read(bytes);
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
finally {{
try
try {{
if
if (in
(in !=
!= null)
null)
in.close();
in.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
String
String hello
hello == new
new String(bytes,
String(bytes, 0,
0, nbytes);
nbytes);
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(bytes));
System.out.println(hello);
System.out.println(hello);
[72,
[72, 101,
101, 108,
108, 108,
108, 111,
111, 32,
32, 87,
87, 111,
111, 114,
114, 108,
108, 100,
100, 33,
33, 0,
0, 0,
0, ...
... ,, 0,
0, 0,
0, 0,
0, 0,
0, 0]
0]
Hello
World!
Hello World!
26

27.

Буферизованный ввод
27

28. Класс FilterInputStream

public
public class
class FilterInputStream
FilterInputStream extends
extends InputStream
InputStream
{{
protected
protected InputStream
InputStream in;
in;
protected
protected FilterInputStream(InputStream
FilterInputStream(InputStream in)
in) {{
this.in
this.in == in;
in;
}}
public
public int
int read()
read() throws
throws IOException
IOException {{
return
return in.read();
in.read();
}}
public
public int
int read(byte
read(byte b[])
b[]) throws
throws IOException
IOException {{
return
return read(b,
read(b, 0,
0, b.length);
b.length);
}}
public
public int
int read(byte
read(byte b[],
b[], int
int off,
off, int
int len)
len) throws
throws IOException
IOException {{
return
return in.read(b,
in.read(b, off,
off, len);
len);
}}
}}
public
public void
void close()
close() throws
throws IOException
IOException {{
in.close();
in.close();
}}
C
Класс FilterInputStream – базовый класс для всех фильтрующих потоков ввода. Эти классы оборачивают
существующий поток ввода который используется как источник данных возможно преобразуя данные или
предоставляя дополнительную функциональность. Класс FilterInputStream просто переопределяет все
методы класса InputStream версиями которые перенаправляют все запросы оборачиваемому потоку.
Классы потомки FilterInputStream могут переопределять эти методы, а также предоставлять
дополнительные методы и поля.
28

29. Класс BufferedInputStream

public
public class
class
{{
protected
protected
protected
protected
protected
protected
BufferedInputStream
BufferedInputStream extends
extends FilterInputStream
FilterInputStream
byte[]
byte[] buf
buf
int
int count;
count;
int
pos;
int pos;
public
public BufferedInputStream(InputStream
BufferedInputStream(InputStream in)
in)
public
public BufferedInputStream(InputStream
BufferedInputStream(InputStream in,
in, int
int size)
size)
}}
public
public
public
public
int
int
int
int
read()
read()
read(byte[]
read(byte[] b,
b, int
int off,
off, int
int len)
len)
C
Класс BufferedInputStream - реализует буферизованный поток
ввода для повышения эффективности чтения данных. В
конструкторе необходимо задать оборачиваемый поток. Для
хранения данных используется массив byte размер которого можно
задать в конструкторе.
29

30. Производительность буферизованного ввода

public
public class
class ReadBufPerform
ReadBufPerform {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
BufferedInputStream
BufferedInputStream inbuf
inbuf == null;
null;
FileInputStream
FileInputStream in
in == null;
null;
int
int temp;
temp;
long
long time
time == System.currentTimeMillis();
System.currentTimeMillis();
try
try {{
inbuf
inbuf == new
new BufferedInputStream(new
BufferedInputStream(new FileInputStream(
FileInputStream(
"I:\\FileIO\\outbuf.dat"));
"I:\\FileIO\\outbuf.dat"));
}}
}}
for
for (int
(int ii == 0;
0; ii << 10000000;
10000000; i++)
i++) {{
temp
temp == inbuf.read();
inbuf.read();
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
{
finally {
try
try {{
if
if (inbuf
(inbuf !=
!= null)
null)
inbuf.close();
inbuf.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
time
time == System.currentTimeMillis()
System.currentTimeMillis() -- time;
time;
System.out.println("Buffered
System.out.println("Buffered input
input time:
time: "" ++ time);
time);
...
...
30

31. Производительность небуферизованного ввода

public
public class
class ReadBufPerform
ReadBufPerform {{
public
public static
static void
void main(String[]
main(String[] args)
args) throws
throws IOException
IOException {{
...
...
time
time == System.currentTimeMillis();
System.currentTimeMillis();
try
try {{
in
in == new
new FileInputStream("I:\\FileIO\\outnobuf.dat");
FileInputStream("I:\\FileIO\\outnobuf.dat");
}}
}}
for
for (int
(int ii == 0;
0; ii << 10000000;
10000000; i++)
i++) {{
temp
temp == in.read();
in.read();
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("An
System.out.println("An I/O
I/O error
error occured");
occured");
}} finally
finally {{
try
try {{
if
if (in
(in !=
!= null)
null)
in.close();
in.close();
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
time
time == System.currentTimeMillis()
System.currentTimeMillis() -- time;
time;
System.out.println("Non-buffered
System.out.println("Non-buffered input
input time:
time: "" ++ time);
time);
Buffered
Buffered input
input time:
time: 375
375
Non-buffered
Non-buffered input
input time:
time: 10031
10031
31
English     Русский Правила