黑马程序员 IO流

来源:互联网 发布:系统优化级别选哪个好 编辑:程序博客网 时间:2024/04/29 03:13

 -------android培训、java培训、期待与您交流! ----------

 

IO流部分主要是类的使用,方法的使用,注意格式。此部分以例题代码为主,注意各个方法的细节特点,熟练应用。

 

字节流两个基类:InputStream   OutputStream。

字符流两个基类:Reader Writer。

FileWriter对象。该对象一被初始化就必须要明确被操作的文件。而且该文件会被创建到指定目录下。如果该目录下已有同名文件,将被覆盖。

flush()方法:刷新流对象中的缓冲中的数据,将数据刷到目的地中。

close()方法:关闭流资源,但是关闭之前会刷新一次内部的缓冲中的数据。

IO异常的处理例:

import java.io.*;class  FileWriterDemo2{public static void main(String[] args) {FileWriter fw = null;try{fw = new FileWriter("demo.txt");fw.write("abcdefg");}catch (IOException e){System.out.println("catch:"+e.toString());}finally{try{if(fw!=null)fw.close();}catch (IOException e){System.out.println(e.toString());}}}}

FileWriter fw = new FileWriter("demo.txt",true)  此例中传递一个true参数,代表不覆盖已有的文件。并在已有文件的末尾处进行数据续写。

IO联系例,将一个文件复制

import java.io.*;class CopyText {public static void main(String[] args) throws IOException{copy_2();}public static void copy_2(){FileWriter fw = null;FileReader fr = null;try{fw = new FileWriter("SystemDemo_copy.txt");fr = new FileReader("SystemDemo.java");char[] buf = new char[1024];int len = 0;while((len=fr.read(buf))!=-1){fw.write(buf,0,len);}}catch (IOException e){throw new RuntimeException("读写失败");}finally{if(fr!=null)try{fr.close();}catch (IOException e){}if(fw!=null)try{fw.close();}catch (IOException e){}}}public static void copy_1()throws IOException{//创建目的地。FileWriter fw = new FileWriter("RuntimeDemo_copy.txt");//与已有文件关联。FileReader fr = new FileReader("RuntimeDemo.java");int ch = 0;while((ch=fr.read())!=-1){fw.write(ch);}fw.close();fr.close();}}

缓冲区的出现是为了提高流的操作效率而出现的。所以在创建缓冲区之前,必须要先有流对象。

BufferedWriter缓冲区中提供了一个跨平台的换行符:newLine()。

BufferedReader缓冲区提供了一个一次读一行的方法 readLine,方便于对文本数据的获取。当返回null时,表示读到文件末尾。

装饰设计模式:

当想要对把有的对象进行功能增强时,可以定义类。将已有对象传入,基于已有的功能,并提供加强功能,那么自定义的该类称为装饰类。

 

字节流例,图片的复制:

import java.io.*;class  CopyPic{public static void main(String[] args) {FileOutputStream fos = null;FileInputStream fis = null;try{fos = new FileOutputStream("c:\\2.bmp");fis = new FileInputStream("c:\\1.bmp");byte[] buf = new byte[1024];int len = 0;while((len=fis.read(buf))!=-1){fos.write(buf,0,len);}}catch (IOException e){throw new RuntimeException("复制文件失败");}finally{try{if(fis!=null)fis.close();}catch (IOException e){throw new RuntimeException("读取关闭失败");}try{if(fos!=null)fos.close();}catch (IOException e){throw new RuntimeException("写入关闭失败");}}}}

mp3的复制:

import java.io.*;class  CopyMp3{public static void main(String[] args) throws IOException{long start = System.currentTimeMillis();copy_2();long end = System.currentTimeMillis();System.out.println((end-start)+"毫秒");}public static void copy_2()throws IOException{MyBufferedInputStream bufis = new MyBufferedInputStream(new FileInputStream("c:\\9.mp3"));BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("c:\\3.mp3"));int by = 0;//System.out.println("第一个字节:"+bufis.myRead());while((by=bufis.myRead())!=-1){bufos.write(by);}bufos.close();bufis.myClose();}//通过字节流的缓冲区完成复制。public static void copy_1()throws IOException{BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("c:\\0.mp3"));BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("c:\\1.mp3"));int by = 0;while((by=bufis.read())!=-1){bufos.write(by);}bufos.close();bufis.close();}}

通过键盘录入数据。

当录入一行数据后,就将该行数据进行打印。如果录入的数据是over,那么停止录入。

import java.io.*;class  ReadIn{public static void main(String[] args) throws IOException{InputStream in = System.in;StringBuilder sb = new StringBuilder();while(true){int ch = in.read();if(ch=='\r')continue;if(ch=='\n'){String s = sb.toString();if("over".equals(s))break;System.out.println(s.toUpperCase());sb.delete(0,sb.length());}elsesb.append((char)ch);}}}

键盘录入,控制台输出的综合例题(含字节转字符,字符转字节)

import java.io.*;class  TransStreamDemo{public static void main(String[] args) throws IOException{//键盘的最常见写法。BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));String line = null;while((line=bufr.readLine())!=null){if("over".equals(line))break;bufw.write(line.toUpperCase());bufw.newLine();bufw.flush();}bufr.close();}}

流操作的基本规律:

通过三个明确来完成。

1,明确源和目的。

源:输入流。InputStream  Reader

目的:输出流。OutputStream  Writer。

2,操作的数据是否是纯文本。

是:字符流。不是:字节流。

3,当体系明确后,在明确要使用哪个具体的对象。

通过设备来进行区分:

源设备:内存,硬盘。键盘

目的设备:内存,硬盘,控制台。

system类中setIn与setOut方法:

class  TransStreamDemo2{public static void main(String[] args) throws IOException{System.setIn(new FileInputStream("PersonDemo.java"));System.setOut(new PrintStream("zzz.txt"));//键盘的最常见写法。BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));String line = null;while((line=bufr.readLine())!=null){if("over".equals(line))break;bufw.write(line.toUpperCase());bufw.newLine();bufw.flush();}bufr.close();}}

File类常见方法:
1,创建。
boolean createNewFile():在指定位置创建文件,如果该文件已经存在,则不创建,返回false。和输出流不一样,输出流对象一建立创建文件。而且文件已经存在,会覆盖。

boolean mkdir():创建文件夹。

boolean mkdirs():创建多级文件夹。

2,删除。

boolean delete():删除失败返回false。如果文件正在被使用,则删除不了返回falsel。

void deleteOnExit();在程序退出时删除指定文件。

3,判断。

boolean exists() :文件是否存在.

isFile();isDirectory();isHidden();isAbsolute()。

4,获取信息。

getName();getPath();getParent();getAbsolutePath();long lastModified();long length() 。

列出指定目录下文件或者文件夹,包含子目录中的内容。也就是列出指定目录下所有内容。

因为目录中还有目录,只要使用同一个列出目录功能的函数完成即可。在列出过程中出现的还是目录的话,还可以再次调用本功能。也就是函数自身调用自身。这种表现形式,或者编程手法,称为递归。

递归要注意:
1,限定条件。

2,要注意递归的次数。尽量避免内存溢出。

import java.io.*;class FileDemo3 {public static void main(String[] args) {File dir = new File("d:\\testdir");System.out.println(dir.delete());}public static String getLevel(int level){StringBuilder sb = new StringBuilder();sb.append("|--");for(int x=0; x<level; x++){//sb.append("|--");sb.insert(0,"|  ");}return sb.toString();}public static void showDir(File dir,int level){System.out.println(getLevel(level)+dir.getName());level++;File[] files = dir.listFiles();for(int x=0; x<files.length; x++){if(files[x].isDirectory())showDir(files[x],level);elseSystem.out.println(getLevel(level)+files[x]);}}

例:将一个指定目录下的java文件的绝对路径,存储到一个文本文件中。建立一个java文件列表文件。

1,对指定的目录进行递归。

2,获取递归过程所以的java文件的路径。

3,将这些路径存储到集合中。

4,将集合中的数据写入到一个文件中。

import java.io.*;import java.util.*;class  JavaFileList{public static void main(String[] args) throws IOException{File dir = new File("d:\\java1223");List<File> list = new ArrayList<File>();fileToList(dir,list);//System.out.println(list.size());File file = new File(dir,"javalist.txt");writeToFile(list,file.toString());}public static void fileToList(File dir,List<File> list){File[] files = dir.listFiles();for(File file : files){if(file.isDirectory())fileToList(file,list);else{if(file.getName().endsWith(".java"))list.add(file);}}}public static void writeToFile(List<File> list,String javaListFile)throws IOException{BufferedWriter bufw =  null;try{bufw = new BufferedWriter(new FileWriter(javaListFile));for(File f : list){String path = f.getAbsolutePath();bufw.write(path);bufw.newLine();bufw.flush();}}catch (IOException e){throw e;}finally{try{if(bufw!=null)bufw.close();}catch (IOException e){throw e;}}}}

Properties是hashtable的子类。也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串。是集合中和IO技术相结合的集合容器。

该对象的特点:可以用于键值对形式的配置文件。那么在加载数据时,需要数据有固定格式:键=值。

import java.io.*;import java.util.*;class PropertiesDemo {public static void main(String[] args) throws IOException{//method_1();loadDemo();}public static void loadDemo()throws IOException{Properties prop = new Properties();FileInputStream fis = new FileInputStream("info.txt");//将流中的数据加载进集合。prop.load(fis);prop.setProperty("wangwu","39");FileOutputStream fos = new FileOutputStream("info.txt");prop.store(fos,"haha");//System.out.println(prop);prop.list(System.out);fos.close();fis.close();}//演示,如何将流中的数据存储到集合中。//想要将info.txt中键值数据存到集合中进行操作。public static void method_1()throws IOException{BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));String line = null;Properties prop = new Properties();while((line=bufr.readLine())!=null){String[] arr = line.split("=");///System.out.println(arr[0]+"...."+arr[1]);prop.setProperty(arr[0],arr[1]);}bufr.close();System.out.println(prop);}}

练习:用于记录应用程序运行次数。如果使用次数已到,那么给出注册提示。
注意:

程序即使结束,该计数器的值也存在。下次程序启动在会先加载该计数器的值并加1后在重新存储起来。所以要建立一个配置文件。用于记录该软件的使用次数。

import java.io.*;import java.util.*;class  RunCount{public static void main(String[] args) throws IOException{Properties prop = new Properties();File file = new File("count.ini");if(!file.exists())file.createNewFile();FileInputStream fis = new FileInputStream(file);prop.load(fis);int count = 0;String value = prop.getProperty("time");if(value!=null){count = Integer.parseInt(value);if(count>=5){System.out.println("您好,使用次数已到,拿钱!");return ;}}count++;prop.setProperty("time",count+"");FileOutputStream fos = new FileOutputStream(file);prop.store(fos,"");fos.close();fis.close();}}

文件的切割和合并。SequenceInputStream类的使用:

import java.io.*;import java.util.*;class SplitFile {public static void main(String[] args) throws IOException{//splitFile();merge();}public static void merge()throws IOException{ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();for(int x=1; x<=3; x++){al.add(new FileInputStream("c:\\splitfiles\\"+x+".part"));}final Iterator<FileInputStream> it = al.iterator();Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){public boolean hasMoreElements(){return it.hasNext();}public FileInputStream nextElement(){return it.next();}};SequenceInputStream sis = new SequenceInputStream(en);FileOutputStream fos = new FileOutputStream("c:\\splitfiles\\0.bmp");byte[] buf = new byte[1024];int len = 0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}public static void splitFile()throws IOException{FileInputStream fis =  new FileInputStream("c:\\1.bmp");FileOutputStream fos = null;byte[] buf = new byte[1024*1024];int len = 0;int count = 1;while((len=fis.read(buf))!=-1){fos = new FileOutputStream("c:\\splitfiles\\"+(count++)+".part");fos.write(buf,0,len);fos.close();}fis.close();}}

管道流,连接输入与输出:

例:

import java.io.*;class Read implements Runnable{private PipedInputStream in;Read(PipedInputStream in){this.in = in;}public void run(){try{byte[] buf = new byte[1024];System.out.println("读取前。。没有数据阻塞");int len = in.read(buf);System.out.println("读到数据。。阻塞结束");String s= new String(buf,0,len);System.out.println(s);in.close();}catch (IOException e){throw new RuntimeException("管道读取流失败");}}}class Write implements Runnable{private PipedOutputStream out;Write(PipedOutputStream out){this.out = out;}public void run(){try{System.out.println("开始写入数据,等待6秒后。");Thread.sleep(6000);out.write("piped lai la".getBytes());out.close();}catch (Exception e){throw new RuntimeException("管道输出流失败");}}}class  PipedStreamDemo{public static void main(String[] args) throws IOException{PipedInputStream in = new PipedInputStream();PipedOutputStream out = new PipedOutputStream();in.connect(out);Read r = new Read(in);Write w = new Write(out);new Thread(r).start();new Thread(w).start();}}

有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括姓名,三门课成绩),输入的格式:如:zhagnsan,30,40,60计算出总成绩,并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。

1,描述学生对象。

2,定义一个可操作学生对象的工具类。

思想:

1,通过获取键盘录入一行数据,并将该行中的信息取出封装成学生对象。

2,因为学生有很多,那么就需要存储,使用到集合。因为要对学生的总分排序,所以可以使用TreeSet。

3,将集合的信息写入到一个文件中。

import java.io.*;import java.util.*;class Student implements Comparable<Student>{private String name;private int ma,cn,en;private int sum;Student(String name,int ma,int cn,int en){this.name = name;this.ma = ma;this.cn = cn;this.en = en;sum = ma + cn + en;}public int compareTo(Student s){int num = new Integer(this.sum).compareTo(new Integer(s.sum));if(num==0)return this.name.compareTo(s.name);return num;}public String getName(){return name;}public int getSum(){return sum;}public int hashCode(){return name.hashCode()+sum*78;}public boolean equals(Object obj){if(!(obj instanceof Student))throw new ClassCastException("类型不匹配");Student s = (Student)obj;return this.name.equals(s.name) && this.sum==s.sum;}public String toString(){return "student["+name+", "+ma+", "+cn+", "+en+"]";}}class StudentInfoTool{public static Set<Student> getStudents()throws IOException{return getStudents(null);}public static Set<Student> getStudents(Comparator<Student> cmp)throws IOException{BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;Set<Student> stus  = null;if(cmp==null)stus = new TreeSet<Student>();elsestus = new TreeSet<Student>(cmp);while((line=bufr.readLine())!=null){if("over".equals(line))break;String[] info = line.split(",");Student stu = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));stus.add(stu);}bufr.close();return stus;}public static void write2File(Set<Student> stus)throws IOException{BufferedWriter bufw = new BufferedWriter(new FileWriter("stuinfo.txt"));for(Student stu : stus){bufw.write(stu.toString()+"\t");bufw.write(stu.getSum()+"");bufw.newLine();bufw.flush();}bufw.close();}}class StudentInfoTest {public static void main(String[] args) throws IOException{Comparator<Student> cmp = Collections.reverseOrder();Set<Student> stus = StudentInfoTool.getStudents(cmp);StudentInfoTool.write2File(stus);}}


 

原创粉丝点击