JAVA I/O编程

来源:互联网 发布:中药软件哪好用 编辑:程序博客网 时间:2024/04/27 14:43
IO(Input  Output)流,

IO流用来处理设备之间的数据传输




------- android培训java培训IOS培训.Net培训期待与您交流! ----------


File类



用来将文件或者文件夹封装成对象


方便对文件与文件夹的属性信息进行操作。


File对象可以作为参数传递给流的构造函数。


流按操作数据分为两种:字节流与字符流。
流按流向分为:输入流(读),输出流(写)


字节流
运用FileInputStream和FileOutputStream类读写文本文件
运用DataInputStream和DataOutputStream类读写二进制文件
字符流
运用BufferedReader和PrintWriter类读写文本文件
注:由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀。
如:InputStream的子类FileInputStream。
如:Reader的子类FileReader。







01<font size="3"><code id="code0">publicclassTestFile {
02    publicstaticvoidmain(String[] args) {
03        File f =newFile("c:\\temp.txt");
04        if(!f.exists()){
05            try{
06                f.createNewFile();
07            }catch(IOException ex) {
08               ex.printStackTrace();
09            }
10        }
11        System.out.println("是文件吗:"+ f.isFile());
12        System.out.println("是目录吗:"+ f.isDirectory());
13        System.out.println("名称:"+ f.getName());
14        System.out.println("路径: "+ f.getPath());
15        System.out.println("绝对路径: "+ f.getAbsolutePath());
16        System.out.println("最后修改时间:"+newDate(f.lastModified()));
17        System.out.println("文件大小:"+ f.length()+"字节");
18        System.out.println("文件可读吗:"+f.canRead());
19        System.out.println("文件可写吗:"+f.canWrite());            
20    }  
21}</code></font>



所谓流(stream),是指有序的数据序列,它有一个来源(输入流)或者目的地(输出流)
输入输出(input/output)也称I/O。从任何能够发送数据的地方(数据源)可以取得“输入”对象;通过“输出”对象可以发送数据到任何能够接收字节的地方(输出的目的地)
如图详解:


Java流的分类
字节流:8 位
InputStream :字节输入流
OutputStream:字节输出流
字符流16 位 Unicode
Reader :字符输入流
Writer :字符输出流



字节流读写文件
InputStream和OutputStream是用于读取或者写入字节的字节流, InputStream和OutputStream是两个抽象类,还不能表明对应哪种IO设备,它下面有许多子类,包括网络,管道,内存,文件等具体的IO设备
FileInputStream和FileOutputStream分别是InputStream和OutputStream的子类,用来操作磁盘文件,实现从指定的文件中获取字节和将字节写入指定的文件
例如:

01public class TestByteIO {
02    publicstaticvoidmain(String[] args) {
03        File f =newFile(“c:\\temp.txt”);//创建文件对象
04        try{
05              //通过文件对象创建文件输出流
06            FileOutputStream fileout =newFileOutputStream(f);
07            String outstr ="这是写入文件的数据";
08            bytebuf[] = outstr.getBytes();//将字符串转化成字节
09            fileout.write(buf);//将字节写入文件
10            fileout.close();  //关闭输出流
11        }catch(IOException ex) {
12           ex.printStackTrace();
13        }try{[/size]
14[size=3]           // 通过文件对象创建文件输入流[/size]
15[size=3]            FileInputStream filein =newFileInputStream(f);[/size]
16[size=3]         //创建字节数组,用于接收从文件中读取的字节[/size]
17[size=3]            bytebuf[] =newbyte[1024];[/size]
18[size=3]            String instr ="";//接收字节转化的字符串[/size]
19[size=3]            intlength = filein.read(buf);[/size]
20[size=3]            instr =newString(buf,0,length);//将字节转化成字符串   [/size]
21[size=3]            System.out.println(instr);[/size]
22[size=3]            filein.close();  //关闭输入流[/size]
23[size=3]        }catch(IOException ex) {[/size]
24[size=3]           ex.printStackTrace();[/size]
25[size=3]        }[/size]
26[size=3]    }[/size]
27[size=3]} [/size]
28[size=3]
29[/size]
30[size=3]

注意:
定义文件路径时,可以用“/”或者“\\”。
在创建一个文件时,如果目录下有同名文件将被覆盖。
在读取文件时,必须保证该文件已存在,否则出异常





文件读写步骤
创建文件对象:File  f = new File(“文件路径”);
根据文件对象创建输入输出流
FileInputStream filein = new FileInputStream(f);
FileOutputStream fileout = new FileOutputStream(f);
实现对文件的读写
读:filein.read(字节数组);//将文件内容读到指定的字节数组
写:fileout.write(字节数组);//将指定字节数组中的数据写到文件
关闭流
filein.close();
fileout.close();

FileInputStream和FileOutputStream只提供了读写字节的方法,在实际应用中,需要向文件中写入或读取各种类型的数据,那就必须先将其他类型的数据转换成字节数组后写入文件或将从文件中读取的字节数组转换成其他数据类型


字节过滤流
DataInputStream:继承自FilterInputStream,允许应用程序以与机器无关方式从基础输入流中读取java基本数据类型
构造方法
DataInputStream datain = new DataInputStream(基础输入流);   
DataOutputStream:继承自FilterOutputStream,允许应用程序以适当方式将java基本数据类型写入输出流中
构造方法
DataOutputStream datain = new DataOutputStream(基础输出流);
实现对二进制文件的读写

如图详解:


文件对象:
File f = new File(“c:\\temp.txt”);
输入过滤流
FileInputStream filein = new FileInputStream(f);
DataInputStream datain = new DataInputStream(filein);
输出过滤流
FileOutputStream fileout = new FileOutputStream(f);
DataOutputStream dataout = new DataOutputStream(fileout);


01public class TestDataIO {
02    publicstaticvoidmain(String[] args) {
03        File f =newFile("c:\\temp.txt");
04        try{
05            //   通过文件对象创建文件输出流
06            FileOutputStream fileout =newFileOutputStream(f);
07            DataOutputStream dataout =newDataOutputStream(fileout);
08            intid =1;
09            String name ="张三";
10            doublemoney =5000.0;
11            dataout.writeInt(id);//写入整型数据
12            dataout.writeUTF(name);//写入字符型数据
13            dataout.writeDouble(money);//写入双精度数据
14            dataout.close();//关闭流
15        }catch(IOException ex) {
16            ex.printStackTrace();
17        }try{
18           //   通过文件对象创建文输入流
19           FileInputStream filein =newFileInputStream(f);
20           DataInputStream datain =newDataInputStream(filein);
21            intid =0;
22            doublemoney =0;
23            String name ="";
24            id = datain.readInt();//读取整型数据
25            name = datain.readUTF();//读取字符串数据  
26            money = datain.readDouble();//读取双精度数据
27            System.out.println("帐户信息为:"+ id +"  "+ name + "  " + money);
28            datain.close();//关闭流
29        }catch(IOException ex) {
30            ex.printStackTrace();
31        }
32    }
33}



字符流读写文件
Reader和Writer是用于读取或者写入字符的字符流, Reader和Writer是两个抽象类,还不能表明对应哪种IO设备,它下面有许多子类,包括网络,管道,内存,文件等具体的IO设备,见,java.io包结构(P227)
InputStreamReader和InputStreamWriter分别是Reader和Writer的子类,作为从字节流到字符流的转换
FileReader和FileWriter分别是InputStreamReader和InputStreamWriter的子类,用来操作磁盘文件,实现从指定的文件中读取字符和将字符写入指定的文件

案例:

01public class TestStringIO {
02    publicstaticvoidmain(String[] args) {
03        File f =newFile("c:\\temp.txt");
04        try{
05            FileWriter fw =newFileWriter(f);//创建文件字符流对象
06            String id ="2009001";
07            String name ="张三";
08            String sex ="男";
09            intage =20;
10            Integer integerNum =newInteger(age);//使用包装类将基本数据类型转化成字符串
11            String strage = integerNum.toString();
12            //写文件,FileWriter继承了Writer类的所有方法
13            fw.write(id);  
14            fw.write(name);
15            fw.write(sex);
16            fw.write(strage);
17            //关闭流
18            fw.close();
19        }catch(IOException ex) {
20             ex.printStackTrace();
21        }//读取文件[/size]
22[size=3]try{[/size]
23[size=3]         FileReader fr =newFileReader(f);//创建文件字符流对象[/size]
24[size=3]         //创建字符数组,接收读取的数据[/size]
25[size=3]         char[] buf =newchar[1000];[/size]
26[size=3]         //读取文件内容到buf,返回实际数据的长度[/size]
27[size=3]         intlength = fr.read(buf);[/size]
28[size=3]         //将字符数组转成字符串[/size]
29[size=3]         String readStr =newString(buf,0,length);[/size]
30[size=3]         System.out.println(readStr);[/size]
31[size=3]         //关闭流[/size]
32[size=3]         fr.close();    [/size]
33[size=3]        }catch(IOException ex){[/size]
34[size=3]            ex.printStackTrace();[/size]
35[size=3]        }[/size]
36[size=3]  }[/size]
37[size=3]}

FileWriter提供了写字符串的方法,可以直接将字符串写进文件:public void write(String str) throws IOException;FileReader没有提供读字符串的方法,只能一次性读取所有字符,将字符存储在字符数组中,在需要的情况下将字符数组转成字符串处理;


字符过滤流
BufferedReader:继承自Reader,从字符输入流中读取文本,缓冲各个字符,提供字符,数组和行的高效读取
常用构造方法
BufferedReader bufferedin = new BufferedReader(Reader对象);   
PrintWriter:继承自Writer,  向文本输出流打印对象的格式化表示形式,常用的方法为print和println
常用构造方法
PrintWriter pw = new PrintWriter(Writer 对象);

案例:

1public class Student {    privateString ID;   privateString name;   privateString address;   privateString email;   publicstaticString SEPARATOR=“:”;//分隔符   //无参构造   public Student() {    }//有参构造    public Student(String ID, String name, String address, String email) {        this.ID = ID;        this.name = name;        this.address = address;        this.email = email;    }   //get和set略   //toString()方法(显示详细信息)}public class TestStringFilterIO { public static void main(String[] args) {        File f = new File("c:\\temp.txt");        try {            FileWriter fw = new FileWriter(f);//创建文件字符流对象            PrintWriter pw = new PrintWriter(fw);//创建输出过滤流            //创建学生对象            Student stu = new Student("2009001","杨过","桃花岛","yangguo@taohuadao.com");            //向文件中写入数据,注意在单个数据后加分割符,以便读取数据后根据分隔符区分属性值            pw.println(stu.getID()+Student.SEPARATOR+stu.getName()+Student.SEPARATOR+                    stu.getAddress()+Student.SEPARATOR+stu.getEmail());            //关闭流            pw.close();        } catch (IOException ex) {             ex.printStackTrace();        }try {            FileReader fr = new FileReader(f);//创建文件字符流对象            BufferedReader bufferedin = new BufferedReader(fr);            String line = bufferedin.readLine();//从文件中读取一行数据            //拆分字符串            String[] datas = line.split(Student.SEPARATOR);//将拆分后的字符存入字符串数组                        //创建学生对象            Student stu = new Student(datas[0],datas[1],datas[2],datas[3]);            String stustr = stu.toString();//将对象信息转换成字符串            System.out.println(stustr);            //关闭流            bufferedin.close();        } catch (IOException ex) {             ex.printStackTrace();        }          }}


file.PNG


file构造方法.png


常用的方法.png


流.PNG


输入输出流.png



字节过滤流.PNG

0 0
原创粉丝点击