Similar presentations:
Ввод – вывод. Потоки данных
1.
2.
V. Ввод – вывод4. Потоки данных
2
3. Потоки данных
Объект из которого можно последовательно прочитать значения примитивных типовназывается поток ввода данных. Объект в который можно последовательно записать
значения примитивных типов называется поток вывода данных. Классом для потоков
ввода данных является класс DataInputStream, а потоков вывода данных класс
DataOutputStream. Классы потоков данных находятся в пакете java.io.
3
4.
Потоки вывода данных4
5. Класс DataOutputStream
56. Класс DataOutputStream
publicpublic class
class DataOutputStream
DataOutputStream extends
extends FilterOutputStream
FilterOutputStream {{
protected
protected int
int written;
written;
private
byte[]
private byte[] bytearr
bytearr == null;
null;
public
public final
final int
int size()
size()
public
public DataOutputStream(OutputStream
DataOutputStream(OutputStream out)
out)
private
private void
void incCount(int
incCount(int value)
value)
}}
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
final
final
final
final
final
final
final
final
final
final
final
final
final
final
final
final
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
writeBoolean(boolean
writeBoolean(boolean v)
v)
writeByte(int
writeByte(int v)
v)
writeShort(int
writeShort(int v)
v)
writeChar(int
v)
writeChar(int v)
writeInt(int
writeInt(int v)
v)
writeLong(long
writeLong(long v)
v)
writeFloat(float
writeFloat(float v)
v)
writeDouble(double
writeDouble(double v)
v)
public
public
public
public
public
public
static
static
final
final void
void writeBytes(String
writeBytes(String s)
s)
final
final void
void writeChars(String
writeChars(String s)
s)
final
final void
void writeUTF(String
writeUTF(String str)
str)
int
writeUTF(String
str,
DataOutput
int writeUTF(String str, DataOutput out)
out)
public
public void
void flush()
flush()
C
Класс DataOutputStream предназначен для превращения примитивов и строк в последовательность байтов и
запись этой последовательности в байтовый поток вывода. Байтовый поток вывода задаётся в конструкторе.
Класс позволяет хранить и получать число записанных байт.
6
7.
Потоки ввода данных7
8. Класс DataInputStream
89. Класс DataInputStream
publicpublic class
class DataInputStream
DataInputStream extends
extends FilterInputStream
FilterInputStream implements
implements DataInput
DataInput {{
public
public DataInputStream(InputStream
DataInputStream(InputStream in)
in)
public
public final
final int
int read(byte
read(byte b[])
b[])
public
public final
final int
int read(byte
read(byte b[],
b[], int
int off,
off, int
int len)
len)
}}
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
final
final
final
final
final
final
final
final
final
final
final
final
final
final
final
final
final
final
boolean
boolean readBoolean()
readBoolean()
byte
readByte()
byte readByte()
short
short readShort()
readShort()
int
int readInt()
readInt()
long
long readLong()
readLong()
float
float readFloat()
readFloat()
double
double readDouble()
readDouble()
String
String readUTF()
readUTF()
static
static String
String readUTF(DataInput
readUTF(DataInput in)
in)
C
Класс DataInputStream предназначен для
чтения примитивов и строк из байтового потока
ввода. Байтовый поток ввода задаётся в
конструкторе.
9
10.
Запись и чтение значений примитива int10
11. Запись int в файл
publicpublic class
class WriteIntDemo
WriteIntDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String
String file
file == "I:\\FileIO\\writeint.txt";
"I:\\FileIO\\writeint.txt";
FileOutputStream
FileOutputStream
DataOutputStream
DataOutputStream
fos
fos
dos
dos
==
==
null;
null;
null;
null;
try
try {{
fos
fos
dos
dos
}}
}}
==
==
new
new
new
new
FileOutputStream(file);
FileOutputStream(file);
DataOutputStream(fos);
DataOutputStream(fos);
for
for (int
(int ii == 0;
0; ii << 64;
64; i++)
i++) {{
dos.writeInt(i);
dos.writeInt(i);
System.out.println(Integer.toBinaryString(i)
System.out.println(Integer.toBinaryString(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 (dos
(dos !=
!= null)
null) {{
dos.close();
dos.close();
}}
}}
catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
11
12. Запись int в файл
0011
10
10
11
11
100
100
101
101
110
110
111
111
1000
1000
1001
1001
1010
1010
1011
1011
1100
1100
1101
1101
1110
1110
1111
1111
10000
10000
...
...
110001
110001
110010
110010
110011
110011
110100
110100
110101
110101
110110
110110
110111
110111
111000
111000
111001
111001
111010
111010
111011
111011
111100
111100
111101
111101
111110
111110
111111
111111
12
13.
1314. Чтение int из файла
publicpublic class
class ReadIntDemo
ReadIntDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String
String file
file == "I:\\FileIO\\WriteInt.txt";
"I:\\FileIO\\WriteInt.txt";
FileInputStream
FileInputStream
DataInputStream
DataInputStream
fis
fis
dis
dis
==
==
null;
null;
null;
null;
try
try {{
fis
fis
dis
dis
==
==
new
new
new
new
FileInputStream(file);
FileInputStream(file);
DataInputStream(fis);
DataInputStream(fis);
int
int temp;
temp;
}}
}}
}}
}}
}}
for
for (int
(int ii == 0;
0; ii << 64;
64; i++)
i++) {{
temp
temp == dis.readInt();
dis.readInt();
System.out.println(temp);
System.out.println(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 (dis
(dis !=
!= null)
null) {{
dis.close();
dis.close();
}}
}}
catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
14
15. Чтение int из файла
0011
22
33
44
55
66
77
88
99
10
10
11
11
...
...
50
50
51
51
52
52
53
53
54
54
55
55
56
56
57
57
58
58
59
59
60
60
61
61
62
62
63
63
15
16.
Запись и чтение примитивов и строки16
17. Запись данных в файл
publicpublic class
class WriteDataDemo
WriteDataDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String
String file
file == "I:\\FileIO\\writedata.dat";
"I:\\FileIO\\writedata.dat";
FileOutputStream
FileOutputStream
DataOutputStream
DataOutputStream
fos
fos
dos
dos
==
==
null;
null;
null;
null;
String
String name
name == "Harry
"Harry Hacker";
Hacker";
char
char gender
gender == 'm';
'm';
boolean
isMarried
boolean isMarried == true;
true;
byte
numChildren
=
2;
byte numChildren = 2;
short
short yearOfBirth
yearOfBirth == 1987;
1987;
int
int salary
salary == 30000;
30000;
long
long netAsset
netAsset == 8234567890L;
8234567890L;
double
weight
=
88.88;
double weight = 88.88;
float
float gpa
gpa == 4.58f;
4.58f;
System.out.println("Name:
System.out.println("Name: "" ++ name);
name);
System.out.println("Gender:
System.out.println("Gender: "" ++ gender);
gender);
System.out.println("Is
married:
"
System.out.println("Is married: " ++ isMarried);
isMarried);
System.out.println("Number
of
children:
System.out.println("Number of children: "" ++ numChildren);
numChildren);
System.out.println("Year
System.out.println("Year of
of birth:
birth: "" ++ yearOfBirth);
yearOfBirth);
System.out.println("Salary:
System.out.println("Salary: "" ++ salary);
salary);
System.out.println("Net
System.out.println("Net Asset:
Asset: "" ++ netAsset);
netAsset);
System.out.println("Weight:
"
+
weight);
System.out.println("Weight: " + weight);
System.out.println("GPA:
System.out.println("GPA: "" ++ gpa);
gpa);
}}
}}
...
...
17
18. Запись данных в файл
publicpublic class
class WriteDataDemo
WriteDataDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
...
...
try
try {{
fos
fos == new
new FileOutputStream(file);
FileOutputStream(file);
dos
dos == new
new DataOutputStream(fos);
DataOutputStream(fos);
dos.writeUTF(name);
dos.writeUTF(name);
dos.writeChar(gender);
dos.writeChar(gender);
dos.writeBoolean(isMarried);
dos.writeBoolean(isMarried);
dos.writeByte(numChildren);
dos.writeByte(numChildren);
dos.writeShort(yearOfBirth);
dos.writeShort(yearOfBirth);
dos.writeInt(salary);
dos.writeInt(salary);
dos.writeLong(netAsset);
dos.writeLong(netAsset);
dos.writeDouble(weight);
dos.writeDouble(weight);
dos.writeFloat(gpa);
dos.writeFloat(gpa);
}}
}}
}} 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 (dos
(dos !=
!= null)
null) {{
dos.close();
dos.close();
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
18
19. Запись данных в файл
Name:Name: Harry
Harry Hacker
Hacker
Gender:
Gender: mm
Is
Is married:
married: true
true
Number
Number of
of children:
children: 22
Year
Year of
of birth:
birth: 1987
1987
Salary:
Salary: 30000
30000
Net
Net Asset:
Asset: 8234567890
8234567890
Weight:
Weight: 88.88
88.88
GPA:
GPA: 4.58
4.58
19
20. Чтение данных из файла
publicpublic class
class ReadDataDemo
ReadDataDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String
String file
file == "I:\\FileIO\\writedata.txt";
"I:\\FileIO\\writedata.txt";
FileInputStream
FileInputStream
DataInputStream
DataInputStream
fis
fis
dis
dis
==
==
null;
null;
null;
null;
try
try {{
...
...
}}
}}
}} 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 (dis
(dis !=
!= null)
null) {{
dis.close();
dis.close();
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
20
21. Чтение данных из файла
publicpublic class
class ReadDataDemo
ReadDataDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
...
...
fis
fis
dis
dis
==
==
new
new
new
new
FileInputStream(file);
FileInputStream(file);
DataInputStream(fis);
DataInputStream(fis);
String
String name
name == dis.readUTF();
dis.readUTF();
char
char gender
gender == dis.readChar();
dis.readChar();
boolean
boolean isMarried
isMarried == dis.readBoolean();
dis.readBoolean();
byte
numChildren
=
dis.readByte();
byte numChildren = dis.readByte();
short
short yearOfBirth
yearOfBirth == dis.readShort();
dis.readShort();
int
int salary
salary == dis.readInt();
dis.readInt();
long
long netAsset
netAsset == dis.readLong();
dis.readLong();
double
double weight
weight == dis.readDouble();
dis.readDouble();
float
gpa
=
dis.readFloat();
float gpa = dis.readFloat();
System.out.println("Name:
System.out.println("Name: "" ++ name);
name);
System.out.println("Gender:
System.out.println("Gender: "" ++ gender);
gender);
System.out.println("Is
System.out.println("Is married:
married: "" ++ isMarried);
isMarried);
System.out.println("Number
of
children:
System.out.println("Number of children: "" ++ numChildren);
numChildren);
System.out.println("Year
of
birth:
"
+
yearOfBirth);
System.out.println("Year of birth: " + yearOfBirth);
System.out.println("Salary:
System.out.println("Salary: "" ++ salary);
salary);
System.out.println("Net
System.out.println("Net Asset:
Asset: "" ++ netAsset);
netAsset);
System.out.println("Weight:
System.out.println("Weight: "" ++ weight);
weight);
System.out.println("GPA:
"
+
gpa);
System.out.println("GPA: " + gpa);
...
...
}}
}}
21
22. Чтение данных из файла
Name:Name: Harry
Harry Hacker
Hacker
Gender:
Gender: mm
Is
Is married:
married: true
true
Number
of
children:
Number of children: 22
Year
Year of
of birth:
birth: 1987
1987
Salary:
Salary: 30000
30000
Net
Net Asset:
Asset: 8234567890
8234567890
Weight:
Weight: 88.88
88.88
GPA:
GPA: 4.58
4.58
22
23.
Запись и чтение состояния объекта23
24. Запись полей класса в файл
classclass Employee
Employee {{
public
public Employee()
Employee() {{
}}
public
public Employee(String
Employee(String name,
name,
boolean
isMarried,
boolean isMarried, int
int
}}
short
short yearOfBirth,
yearOfBirth, char
char gender,
gender,
salary)
{
salary) {
this.name
this.name == name;
name;
this.yearOfBirth
this.yearOfBirth == yearOfBirth;
yearOfBirth;
this.gender
this.gender == gender;
gender;
this.isMarried
this.isMarried == isMarried;
isMarried;
this.salary
=
salary;
this.salary = salary;
public
public String
String toString()
toString() {{
return
return "Employee
"Employee [name="
[name=" ++ name
name ++
++ ",
", gender="
gender=" ++ gender
gender ++ ",
",
++ salary
salary ++ "]";
"]";
}}
...
...
}}
private
private
private
private
private
private
private
private
private
private
",
", yearOfBirth="
yearOfBirth=" ++ yearOfBirth
yearOfBirth
isMarried="
+
isMarried
isMarried=" + isMarried ++ ",
", salary="
salary="
String
String name;
name;
short
short yearOfBirth;
yearOfBirth;
char
char gender;
gender;
boolean
boolean isMarried;
isMarried;
int
salary;
int salary;
24
25. Запись полей класса в файл
classclass Employee
Employee {{
...
...
public
public void
void writeState(String
writeState(String file)
file) {{
FileOutputStream
FileOutputStream
DataOutputStream
DataOutputStream
fos
fos
dos
dos
==
==
null;
null;
null;
null;
try
try {{
fos
fos
dos
dos
==
==
new
new
new
new
FileOutputStream(file);
FileOutputStream(file);
DataOutputStream(fos);
DataOutputStream(fos);
dos.writeUTF(name);
dos.writeUTF(name);
dos.writeShort(yearOfBirth);
dos.writeShort(yearOfBirth);
dos.writeChar(gender);
dos.writeChar(gender);
dos.writeBoolean(isMarried);
dos.writeBoolean(isMarried);
dos.writeInt(salary);
dos.writeInt(salary);
}}
}}
}} 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 (dos
(dos !=
!= null)
null) {{
dos.close();
dos.close();
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
25
26. Запись полей класса в файл
publicpublic class
class DataDemo
DataDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
Employee
Employee bob
bob == new
new Employee("Robert",
Employee("Robert", (short)
(short) 1987,
1987, 'M',
'M', true,
true, 30000);
30000);
System.out.println(bob);
System.out.println(bob);
bob.writeState("bob.dat");
bob.writeState("bob.dat");
}}
}}
...
...
26
27. Запись полей класса в файл
EmployeeEmployee [name=Robert,
[name=Robert, yearOfBirth=1987,
yearOfBirth=1987, gender=M,
gender=M, isMarried=true,
isMarried=true, salary=30000]
salary=30000]
27
28. Чтение полей класса из файла
classclass Employee
Employee {{
...
...
public
public void
void readState(String
readState(String file)
file) {{
FileInputStream
FileInputStream
DataInputStream
DataInputStream
fis
fis
dis
dis
==
==
null;
null;
null;
null;
try
try {{
fis
fis
dis
dis
==
==
new
new
new
new
FileInputStream(file);
FileInputStream(file);
DataInputStream(fis);
DataInputStream(fis);
name
name == dis.readUTF();
dis.readUTF();
yearOfBirth
yearOfBirth == dis.readShort();
dis.readShort();
gender
=
dis.readChar();
gender = dis.readChar();
isMarried
isMarried == dis.readBoolean();
dis.readBoolean();
salary
salary == dis.readInt();
dis.readInt();
}}
}}
}} 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 (dis
(dis !=
!= null)
null) {{
dis.close();
dis.close();
}}
}} catch
catch (IOException
(IOException e)
e) {{
System.out.println("Error
System.out.println("Error closing
closing file");
file");
}}
}}
28
29. Чтение полей класса из файла
publicpublic class
class DataDemo
DataDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
...
...
Employee
Employee robert
robert == new
new Employee();
Employee();
System.out.println(robert);
System.out.println(robert);
}}
}}
robert.readState("bob.dat");
robert.readState("bob.dat");
System.out.println(robert);
System.out.println(robert);
29
30. Чтение полей класса из файла
EmployeeEmployee [name=null,
[name=null, yearOfBirth=0,
yearOfBirth=0, gender=
gender= ,, isMarried=false,
isMarried=false, salary=0]
salary=0]
Employee
Employee [name=Robert,
[name=Robert, yearOfBirth=1987,
yearOfBirth=1987, gender=M,
gender=M, isMarried=true,
isMarried=true, salary=30000]
salary=30000]
30