黑马程序员_IO流(二)

来源:互联网 发布:电纸书推荐 知乎 编辑:程序博客网 时间:2024/05/16 17:43

----------------------ASP.Net+Unity开发、.Net培训、期待与您交流! ---------------------


File概述    File对象功能-创建和删除-判断-获取

    File类:用来将文件或文件夹封装成对象
    方便对文件与文件夹的属性信息进行操作
    File对象可以作为参数传递给流的构造函数

    File类常见方法
        1.创建
            boolean    createNewFile();    在指定位置创建文件,如果已经存在,在不创建,返回false。
            boolean    mkdir();    创建文件夹
            boolean    mkdirs();    创建多级文件夹
        2.删除
            boolean    delete();    删除失败返回false
            void    deleteOnExit();    程序退出时删除
        3.判断
            boolean    exists();    文件是否存在
            boolean    isFile();    判断是否是文件
            boolean    isDirectory();    判断是否是目录
            boolean    isHidden();    判断是否隐藏
            boolean    isAbsolute();    判断是否绝对路径
        4.获取信息
            string    getName();    获取名称
            string    getPath();    获取路径
            string    getParent();    获取父目录
            string    getAbsolutePath();    获取绝对路径
            long    lastModified();    获取最后被修改时间
            long    length();    获取文件大小

public class FileDemo {//创建File对象public static void consMethod(){//将a.txt封装成File对象,可以将已有的和未出现的文件或文件夹封装成对象File f1 = new File("a.txt");File f2 = new File("f:\\abc","b.txt");File d = new File("f:\\abc");File f3 = new File(d,"c.txt");sop("f1:"+f1);sop("f2:"+f2);sop("f3:"+f3);File f4 = new File("f:"+File.separator+"abc"+File.separator+"a.txt");}public static void method_1() throws IOException{File f = new  File("file.txt");sop("create:"+f.createNewFile());    //创建sop("delete:"+f.delete());    //删除}public static void method_2() throws IOException{File f = new  File("file.txt");sop("execute:"+f.exists());    //判断是否存在File dir = new File("abc");sop("dir:"+dir.mkdir());}public static void method_3() throws IOException{File f = new  File("file.txt");//判断文件对象是否是文件或目录时,必须先通过exists判断该文件对象封装的内容是否存在sop("dir:"+f.isDirectory());    //判断是否是目录sop("file:"+f.isFile());    //判断是否是文件sop("isAbsolute:"+f.isAbsolute());    //判断是否绝对路径}public static void method_4() throws IOException{File f = new  File("file.txt");sop("path:"+f.getPath());    //获取路径sop("abspath:"+f.getAbsolutePath());    //获取绝对路径sop("parent:"+f.getParent());    //获取父目录,返回绝对路径中的父目录//如果获取的相对路径,返回null.//如果相对路径由上一层目录,返回上一层目录}public static void method_5() throws IOException{File f1 = new File("file.txt");File f2 = new File("haha.txt");sop("rename:"+f1.renameTo(f2));}public static void sop(Object obj){System.out.println(obj);}public static void main(String[] args) throws IOException {method_2();}}

File对象功能-文件列表

    listRoots();    机器所有盘符
    list();    指定路径所有文件与文件夹,相对路径。
    listFiles();    指定路径所有文件与文件夹,绝对路径。

public class FileDemo2 {public static void listRootsDemo(){File[] files = File.listRoots();for(File f : files){System.out.println(f);}}public static void listDemo(){File f = new File("f:\\");//调用list方法的file对象必须封装了对象,该目录还必须存在String[] names = f.list();for(String name : names){System.out.println(name);}}public static void listDemo_2(){File dir = new File("f:\\");String[] arr = dir.list(new FilenameFilter(){public boolean accept(File dir, String name){return name.endsWith(".mp3");}});System.out.println("len:"+arr.length);for(String name : arr){System.out.println(name);}}public static void main(String[] args) {File dir = new File("f:\\");File[] files = dir.listFiles();for(File f : files){System.out.println(f.getName()+"::"+f.length());}}}

列出目录下所有内容-递归    列出目录下所有内容-带层次

    目录中还有目录,使用同一个列出目录的函数即可
    列出的目录中还有目录,再次调用本功能
    函数自身调用自身,这种编程手法,称为递归

    递归要注意:
        1.限定条件
        2.注意递归次数,避免内存溢出

public class FileDemo3 {public static void showDir(File dir,int level){System.out.println(getLevel(level)+dir);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]);}}public static String getLevel(int level){StringBuilder sb = new StringBuilder();for(int x = 0; x<level; x++){sb.append("|--");}return sb.toString();}public static void main(String[] args) {File dir = new File("f:\\");showDir(dir,0);}}

删除带内容的目录

    从里往外删,需要用到递归

public class RemoveDir {public static void removeDir(File dir){File[] files = dir.listFiles();for(int x=0; x<files.length; x++){if(files[x].isDirectory())removeDir(files[x]);elseSystem.out.println(files[x].toString()+":-file-:"+files[x].delete());}System.out.println(dir+"::dir::"+dir.delete());}public static void main(String[] args) {File dir = new File("f:\\testdir");removeDir(dir);}}

创建java文件列表

    思路:
        1.对指定目录进行递归
        2.获取递归过程中所有的java文件的路径
        3.将这些路径存储到集合中
        4.将集合中的数据写入到一个文件中

public class JavaFileList {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){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 new RuntimeException();}finally{try{if(bufw!=null)bufw.close();}catch(IOException e){throw new RuntimeException();}}}public static void main(String[] args) {File dir = new File("E:\\workspace");List<File> list = new ArrayList<File>();fileToList(dir,list);File file = new File(dir,"javalist.txt");writeToFile(list,file.toString());}}


Properties简述

    Properties是hashtable的子类,具备map集合的特点,它里面存储的键值对都是字符串,不需要泛型。
    是集合中和IO技术相结合的集合容器,该对象的特点:可以用于键值对形式的配置文件。
    在加载数据时,需要数据有固定格式,键-值

Properties存取    Properties存取配置文件

public class PropertiesDemo {public static void method_1() throws IOException{//将info.txt中的键值数据存储到集合进行操作//1.用一个流和info.txt关联//2.读取一行数据,将该行数据用"="切割//3.等号左边为键,右边为值,存入Properties集合即可BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));String line = null;Properties prop = new Properties();while((line=bufr.readLine())!=null){String[] arr = line.split("=");prop.setProperty(arr[0],arr[1]);}bufr.close();System.out.println(prop);}public static void loadDemo() throws IOException{Properties prop = new Properties();FileInputStream fis = new FileInputStream("info.txt");prop.load(fis);System.out.println(prop);prop.setProperty("wangwu", "20");//只改变内存中的数据,文件中不变System.out.println(prop);FileOutputStream fos = new FileOutputStream("info.txt");prop.store(fos, "haha");//改变文件中数据fis.close();fos.close();}public static void setAndGet(){Properties prop = new Properties();prop.setProperty("zhangsan","30");prop.setProperty("lisi", "40");String value = prop.getProperty("lisi");System.out.println(value);Set<String> names = prop.stringPropertyNames();for(String s : names){System.out.println(s+":"+prop.getProperty(s));}}public static void main(String[] args)  throws IOException {//setAndGet();loadDemo();//method_1();}}

Properties练习

    记录程序运行次数
    如果已达到次数,给出提示
    使用计数器
    建立配置文件,使用键值对
    键值对是map集合
    数据以文件形式存储,使用IO技术
    map+io-->properties

/*记录程序运行次数如果已达到次数,给出提示使用计数器建立配置文件,使用键值对键值对是map集合数据以文件形式存储,使用IO技术map+io-->properties*/public 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, "");fis.close();fos.close();}}

PrintWriter

    打印流,提供打印方法,可以将各种数据类型的数据原样打印

    字节打印流:
        PrintStream
            构造函数可以接收的参数类型
            1.file对象
            2.字符串路径 String
            3.字节输出流 OutputStream

    字符打印流:
        PrintWriter
            构造函数可以接收的参数类型
            1.file对象
            2.字符串路径 String
            3.字节输出流 OutputStream
            4.字符输出流

public class PrintStreamDemo {public static void main(String[] args) throws IOException {BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in));PrintWriter out = new PrintWriter(System.out,true);//PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);String line = null;while((line=bufr.readLine())!=null){if("over".equals(line))break;out.println(line.toUpperCase());}bufr.close();out.close();}}

合并流

    多个读取流合并成一个读取流

    Vector:Vector 类可以实现可增长的对象数组。
    Enumeration:枚举。Enumeration接口定义了从一个数据结构得到连续数据的手段。

public class SequenceDemo {public static void main(String[] args) throws IOException{Vector<FileInputStream> v = new Vector<FileInputStream>();v.add(new FileInputStream("1.txt"));v.add(new FileInputStream("2.txt"));v.add(new FileInputStream("3.txt"));Enumeration<FileInputStream> en = v.elements();SequenceInputStream sis = new SequenceInputStream(en);FileOutputStream fos = new FileOutputStream("4.txt");byte[] buf = new byte[1024];int len = 0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}sis.close();fos.close();}}

切割文件

public class SplitFile {public static void split() throws IOException{FileInputStream fis = new FileInputStream("0.jpg");FileOutputStream fos = null;byte[] buf = new byte[1024*1024];int len = 0;int count = 1;while((len=fis.read(buf))!=-1){fos = new FileOutputStream(+(count++)+".part");fos.write(buf,0,len);fos.close();}fis.close();}public static void merge() throws IOException{ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();for(int x=1; x<=4; x++){al.add(new FileInputStream(+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("10.jpg");byte[] buf = new byte[1024];int len = 0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}sis.close();fos.close();}public static void main(String[] args) throws IOException{merge();}}

对象的序列化

    ObjectStreamDemo

public class ObjectStreamDemo {public static void writeObj() throws IOException{ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("obj.txt"));oos.writeObject(new Person("lisi",39,"chn"));oos.close();}public static void readObj() throws Exception{ObjectInputStream ois =new ObjectInputStream(new FileInputStream("obj.txt"));Person p = (Person)ois.readObject();System.out.println(p);ois.close();}public static void main(String[] args) throws Exception {//writeObj();readObj();}}

    Person

public class Person implements Serializable {public static final long serialVersionUID = 42L;private String name;int age;static String country = "chn";Person(String name, int age, String country){this.name = name;this.age = age;this.country = country;}public String toString(){return name+":"+age+":"+country;}}

管道流

class Read implements Runnable{private PipedInputStream in;Read(PipedInputStream in){this.in = in;}public void run(){try{byte[] buf = new byte[1024];int len = in.read(buf);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{out.write("piped".getBytes());out.close();}catch(IOException e){throw new RuntimeException("管道读取流失败");}}}public 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();}}

RandomAccessFile

    该类不算IO体系中的子类,而是直接继承自Object
    但是它是IO包中的成员,因为它具备读和写的功能。
    内部封装了一个数组,通过指针对数组的元素进行操作
    可以通过getFilePointer获取指针位置,同时可以通过seek改变指针的位置
    其实完成读写的原理就是内部封装了字节流。
    通过构造函数可以看出该类只能操作文件,
    而且操作文件还有模式:只读 r 读写 rw 等。
    而且该对象的构造函数要操作的文件不存在,会自动创建,如果存在,不会覆盖。
    如果模式为只读,不归创建文件,回去读取一个已存在的文件,如果文件不存在,会出现异常,如果模式是读写,操作的文件不存在,则会自动创建,如果存在,不会覆盖。

public class RandomAcessFileDemo {public static void writerFile() throws IOException{RandomAccessFile raf = new RandomAccessFile("raf.txt","rw");//调整对象中指针//raf.seek(8);//跳过指定字节数//raf.skipBytes(8);raf.write("李四".getBytes());raf.writeInt(97);raf.write("王五".getBytes());raf.writeInt(99);raf.close();}public static void writeFile_2() throws IOException{RandomAccessFile raf = new RandomAccessFile("raf.txt","rw");raf.seek(8*3);raf.write("周七".getBytes());raf.writeInt(103);raf.close();}public static void readFile() throws IOException{RandomAccessFile raf = new RandomAccessFile("raf.txt","r");//raf.seek(8*3);byte[] buf = new byte[4];raf.read(buf);String name = new String(buf);int age = raf.readInt();System.out.println("name="+name);System.out.println("age="+age);raf.close();}public static void main(String[] args) throws IOException {//writerFile();readFile();//writeFile_2();}}

操作基本数据类型的流对象DataStream

    可以用于操作基本数据类型的流对象

public class DataStreamDemo {public static void writeData() throws IOException{DataOutputStream dos =new DataOutputStream(new FileOutputStream("data.txt"));dos.writeInt(123);dos.writeBoolean(true);dos.writeDouble(9876.543);dos.close();}public static void readData() throws IOException{DataInputStream dis =new DataInputStream(new FileInputStream("data.txt"));int i = dis.readInt();boolean b = dis.readBoolean();double d = dis.readDouble();System.out.println("i="+i);System.out.println("b="+b);System.out.println("d="+d);dis.close();}public static void writeUTFDemo() throws IOException{DataOutputStream dos =new DataOutputStream(new FileOutputStream("utfdata.txt"));dos.writeUTF("你好");dos.close();}public static void readUTFDemo() throws IOException{DataInputStream dis =new DataInputStream(new FileInputStream("utfdata.txt"));String s = dis.readUTF();System.out.println(s);dis.close();}public static void main(String[] args) throws IOException {//writeData();//readData();//writeUTFDemo();//readUTFDemo();}}

ByteArrayStream

    用于操作字节数组的流对象
    ByteArrayInputStream:在构造的时候,需要接收数据源,而且数据源是一个字节数组。
    ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中已经封装了可变长度的字节数组,这就是目的地。
    因为这两个流对象都操作数组,没有使用系统资源,所以不用进行close关闭。

public class ByteArrayStream {public static void main(String[] args) {//数据源ByteArrayInputStream bis = new ByteArrayInputStream("ABCDEF".getBytes());//数据目的ByteArrayOutputStream bos = new ByteArrayOutputStream();int by = 0;while((by=bis.read())!=-1){bos.write(by);}System.out.println(bos.size());System.out.println(bos.toString());}}

转换流的字符编码    

public class EncodeStream {public static void writeText() throws IOException{OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream("gbk.txt"),"GBK");osw.write("你好");osw.close();}public static void readText() throws IOException{InputStreamReader isr =new InputStreamReader(new FileInputStream("gbk.txt"),"GBK");char[] buf = new char[10];int len = isr.read(buf);String str = new String(buf,0,len);System.out.println(str);isr.close();}public static void main(String[] args) throws IOException {//writeText();readText();}}

字符编码

    编码:字符串变成字节数组    String-->byte[]:str.getByte();
    解码:字节数组变成字符串    byte[]-->String:new String(byte[]);

public class EncodeDemo {public static void main(String[] args) throws Exception {String s = "你好";byte[] b1 = s.getBytes("gbk");System.out.println(Arrays.toString(b1));String s1 = new String(b1,"iso8859-1");System.out.println("s1="+s1);//对s1进行iso8859-1编码byte[] b2 = s1.getBytes("iso8859-1");System.out.println(Arrays.toString(b2));String s2 = new String(b2,"gbk");System.out.println("s2="+s2);String s3 = new String(b1,"utf-8");System.out.println("s3="+s3);byte[] b3 = s3.getBytes("utf-8");System.out.println(Arrays.toString(b3));}}

练习
    有五个学生,每个学生有三门成绩,从键盘输入以上数据(包括姓名,三门课成绩),从键盘输入格式:zhangsan,30,40,60    计算出总成绩,并把学生的信息和计算出的总总分数由高到低存放到stuinfo.txt中。
    1.描述学生对象
    2.定义一个可以操作学生对象的工具类
思想:
    1.通过获取键盘录入的一行数据,并将该行中的信息去除封装成学生对象。
    2.存储使用到集合,因为要排序,所以使用TreeSet
    3.将集合中的信息写入文件中

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*39;}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();}}public class StudentInfoTest {public static void main(String[] args) throws IOException {Comparator<Student> cmp = Collections.reverseOrder();Set<Student> stus = StudentInfoTool.getStudents(cmp);StudentInfoTool.write2File(stus);}}





----------------------ASP.Net+Unity开发、.Net培训、期待与您交流! ---------------------

详细请查看:http://edu.csdn.net



0 0