DataInputStream
DataOutputStream
数据流:我自己要明白data是用来操作数据的,也就是java的8大基本数据类型.
一些代码实现:
输入流
/**
*
- @author dch
*/
//字节数据流
public class TestDataInputStream {
public static void main(String[] args) throws Exception {
DataInputStream dis = new DataInputStream(new FileInputStream("d://测试文件夹/aa/aa.txt"));
//跳过N个字节
/*dis.sk ip(6);
boolean flag = dis.readBoolean();
//读int类型
int b = dis.readInt();
//读byte类型
int num = dis.readByte();
System.out.println(flag);
System.out.println(b);
System.out.println(num);*/
int a= dis.readInt();
System.out.println(a);
dis.close();
}
}
输出流和复制文件内容
/**
*
- @author dch
*/
//DataOutputStream
public class TestDataOutputStream {
public static void main(String[] args) throws Exception {
copy1("d://测试文件夹/aa/aa.txt", "d://测试文件夹/bb/bb.txt");
}
public static void method() throws Exception{
//数据流: 将java的8个基本数据类型写入到文件中
DataOutputStream dos = new DataOutputStream(new FileOutputStream("d://测试文件夹/data.txt"));
//一个字节字节写入
dos.write("hello kitty".getBytes());
//dos.writeBoolean(true);
//写入整型
dos.writeInt(123);
dos.writeUTF("hello,你好,我是你爸爸");
//写入布尔值
//dos.writeBoolean(false);
System.out.println("写入成功");
dos.close();
}
//这里是把文件source复制到文件dirsz中
public static void copy1(String source , String dirs) throws Exception{
//先从文件source读出内容
DataInputStream dis = new DataInputStream(new FileInputStream(source));
DataOutputStream dos = new DataOutputStream(new FileOutputStream(dirs));
//自己规定每次读入的大小
//因为是一个字节一个字节的读入
byte [] b = new byte[1024];
//开始复制
//定义一个长度,来保证正常读取文件里面的内容,不存在多读
int len=0;//初始化
//while循环来控制将文件的内容全部读出
//这里因为读完后就会成-1,因此不等于-1的时候就要接着读
long start = System.currentTimeMillis();
while((len=dis.read(b))!=-1){
//将读出的内容在写入到另一个文件当中
//dos.write(b);如果是这样读会造成多读
dos.write(b, 0, len);
}
long end = System.currentTimeMillis();
System.out.println("复制成功,用时: "+(end-start));
dos.close();
dis.close();
}
}
一个小题目
/**
*
- @author dch
*/
//将随机的10 double 输入输出
public class Test1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
/*double [] db = new double[10];
for (int i = 0; i < db.length; i++) {
db[i] = (double)Math.random()*100;
System.out.println(db[i]);
}*/
//先确定把这10个数放进到文件里面
File file = new File("d://测试文件夹/a/a.txt");
//输入流
//OutputStream os = new FileOutputStream(file);
//读出流
InputStream is = new FileInputStream(file);
//data数据流写进到文件夹
//DataOutputStream dos = new DataOutputStream(os);
//data数据里从文件夹读到电脑控制台
DataInputStream dis = new DataInputStream(is);
/*for (int i = 0; i < db.length; i++) {
db[i] = (double)Math.random()*100;
dos.writeDouble(db[i]);
}*/
double [] b1 = new double[10];
for (int i = 0; i < b1.length; i++) {
b1[i]=dis.readDouble();
System.out.println(b1[i]);
}
dis.close();
is.close();
/*System.out.println("写入成功");
dos.close();
os.close();*/
}
}