在IO中提供了两个与平台无关的数据操纵流,一个是数据输出流(DataOutputStream),一个是数据输入流(DataInputStream)
1.DataOutputStream例子
public
class
DataOutputStreamDemo {
public
static
void
main(String[] args)
throws
Exception {
File f =
new
File(
"f:"
+ File.
separator
+
"a.txt"
);
DataOutputStream dos =
new
DataOutputStream(
new
FileOutputStream(f));
String names[]={
"衬衣"
,
"手套"
,
"围巾"
};
float
prices[]={93.9f,85.9f,12,3f};
int
nums[]={3,2,1};
for
(
int
i=0;i<names.
length
;i++){
dos.writeChars(names[i]);
dos.writeChars(
"\t"
);
dos.writeFloat(prices[i]);
dos.writeChars(
"\t"
);
dos.writeInt(nums[i]);
dos.writeChars(
"\n"
);
}
dos.close();
}
}
2.在从a.txt里面读出来
public
class
DataInputStreamDemo {
public
static
void
main(String[] args)
throws
Exception{
File f=
new
File(
"f:"
+File.
separator
+
"a.txt"
);
DataInputStream dis=
new
DataInputStream(
new
FileInputStream(f));
char
temp[]=
new
char
[200];
int
len=0;
String name=
null
;
int
num=0;
float
price=0.0f;
char
c=0;
try
{
while
(
true
){
while
((c=dis.readChar())!=
'\t'
){
temp[len]=c;
len++;
}
name=
new
String(temp,0,len);
price=dis.readFloat();
dis.readChar();
num=dis.readInt();
dis.readChar();
System.
out
.printf(
"名称:%s,价格:%5.2f,数量:%d\n"
,name,price,num);
}
}
catch
(Exception e) {
//
TODO
: handle exception
}
dis.close();
}
}
价格:
名称:衬衣,价格:93.90,数量:3
名称:衬衣手套,价格:85.90,数量:2
名称:衬衣手套围巾,价格:12.00,数量:1
合并流的作用是把两个文件的内容合并到一起
public
class
SequenceDemo {
public
static
void
main(String[] args)
throws
Exception{
File f=
new
File(
"f:"
+File.
separator
+
"a.txt"
);
File f1=
new
File(
"f:"
+File.
separator
+
"b.txt"
);
File f3=
new
File(
"f:"
+File.
separator
+
"ab.txt"
);
InputStream io1=
null
;
//输入流1
InputStream io2=
null
;
//输入流2
OutputStream out=
null
;
//输出流1
SequenceInputStream sis=
null
;
//合并流
io1=
new
FileInputStream(f);
io2=
new
FileInputStream(f1);
out=
new
FileOutputStream(f3);
sis=
new
SequenceInputStream(io1, io2);
int
temp=0;
while
( (temp=sis.read())!=-1){
out.write(temp);
}
sis.close();
io1.close();
io2.close();
out.close();
}
}