黑马程序员_Java基础_IO(2)

来源:互联网 发布:抗战网络电影 编辑:程序博客网 时间:2024/05/22 17:27
------- android培训、java培训、期待与您交流! ----------

 File类
文件和目录路径名的抽象表示形式.
File类的实例可能表示实际文件系统对象,如文件或目录
我们使用File类操作文件和文件夹,然后使用流技术进行各种复制,编写;
也可以通过这个类获取文件或者目录的属性信息;

由于平台性的差异,在操作时使用的前缀
字符串,比如盘符,
 "/" 表示 UNIX 中的根目录,"\\\\" 表示 Microsoft Windows UNC 路径名
 
 
常见方法:
 1.创建
 boolean creatNewFile():在指定位置创建文件,如果该文件已经存在,则不创建,返回false
 和输出流不一样,输出流对象一建立创建文件,而且文件已经存在,会覆盖

 2.删除
 boolean delete():删除失败返回false
 void deleteOnExit()在程序退出时删除指定文件

 3.判断
 boolean exists(); 文件是否存在
 isFile ();
 isDirectory();
 isHidden();
 isAbsolute();
 
 4。获取信息
 getName();
 getPaht();
 getParent();
 getAbsolutePath();
 long lashModified(); 最后一次修改时间
 long length();    文件长度 

例子1: 

public class FileDemo {    public static void main(String[] args) throws IOException {        // method_1();        // method_2();//      method_3();//      method_4();        method_5();    }    public static void method_5() throws IOException {        File f = new File("c:\\");        String[] s = f.list(); //获取C盘目录下的所有文件和文件夹        for(String str : s){            print(str);        }    }    public static void method_4() throws IOException {        File f1 = new File("c:\\Test.txt");        File f2 = new File("d:\\Test01.txt");        print("renameto:" + f1.renameTo(f2));  //将f1剪切到f2中    }    // 创建目录    public static void method_3() throws IOException {        File file = new File("fileDemo.txt");        file.createNewFile();        // 记住在判断文件对象是否是文件或者目录时,必须要先判断该文件对象封装的内容是否存在        // 通过exists判断        print("dir:" + file.isDirectory());        print("file:" + file.isFile());        print(file.isAbsolute()); // 判断路径是否是据对路径    }    public static void method_2() throws IOException {        File file = new File("fileDemo.txt");        // file.createNewFile();        print("exit:" + file.exists()); // 判断是否存在        print("canExecute:" + file.canExecute());// 判断是否可执行        File dir = new File("aa");        dir.mkdir(); // 创建文件夹    }    public static void method_1() throws IOException {        File file = new File("fileDemo.txt");        System.out.println("create:" + file.createNewFile()); // 创建文件        // System.out.println("delete:" + file.delete()); //删除文件        file.deleteOnExit(); // 程序介绍时删除文件 ,我们可以用于临时文件,当系统出现异常是可以使用方法    }    public static void print(Object obj) {        System.out.println(obj);    }}

例子2:

 (重点)
public class FileDemo2 {    public static void main(String[] args) {        method_Fiterfile();    }    // 过滤某个文件夹下的文件 重点    public static void method_Fiterfile() {        File f = new File("c:\\MP3");        String[] fileName = f.list(new FilenameFilter() {            public boolean accept(File dir, String name) {                // 过滤只选择mp3文件                return name.endsWith(".mp3");            }        });        System.out.println("len:" + fileName.length);        for (String name : fileName) {            System.out.println(name);        }    }}
 需求:列出指定目录下的文件或者文件夹  包含子目录中的内容
 也就是列出指定目录下所有的内容
 递归要注意:
 1.限定条件
 2.要注意递归的次数,尽量避免内存溢出
例子3: 
public class FileDemo3 {    public static void main(String[] args) {        File file = new File("D:\\JavaWeb\\workroomHeima\\Heima\\src");        showDir(file,0);    }    //层次    public static String getLevel(int level) {        StringBuilder sb = new StringBuilder();        sb.append("|---");        for(int x =0 ; x<level;x++){            sb.insert(0, "   ");        }        return sb.toString();    }    // 遍历指定目录下的所有文件   有层次的    public static void showDir(File f,int level) {        print(getLevel(level) + f.getName());        level++;        File[] file = f.listFiles();        for (File f1 : file) {            if (f1.isDirectory())                showDir(f1,level);            else                print(getLevel(level)+f1.getName());        }    }    // 将一个整数转换为二进制    public static void toBin(int num) {        if (num > 0) {            toBin(num / 2);            print(num % 2);        }    }    public static void print(Object obj) {        System.out.println(obj);    }}public class FileDemo3 {    public static void main(String[] args) {        File file = new File("D:\\JavaWeb\\workroomHeima\\Heima\\src");        showDir(file,0);    }    //层次    public static String getLevel(int level) {        StringBuilder sb = new StringBuilder();        sb.append("|---");        for(int x =0 ; x<level;x++){            sb.insert(0, "   ");        }        return sb.toString();    }    // 遍历指定目录下的所有文件   有层次的    public static void showDir(File f,int level) {        print(getLevel(level) + f.getName());        level++;        File[] file = f.listFiles();        for (File f1 : file) {            if (f1.isDirectory())                showDir(f1,level);            else                print(getLevel(level)+f1.getName());        }    }    // 将一个整数转换为二进制    public static void toBin(int num) {        if (num > 0) {            toBin(num / 2);            print(num % 2);        }    }    public static void print(Object obj) {        System.out.println(obj);    }}
字符流:
FileReader
FileWriter 
BufferedReader
BufferedWriter
 
字节流:
InputStream
OutputStream
需求:想要操作图片数据,这时就要使用到字节流 
例子4: 
<strong>public class FileStream {    public static void main(String[] args) {        // fileWrite();        // readFile_1();//      readFile_2();        readFile_3();    }    // 第三种读取方式:设置刚好大小的数组进行存储    //这种方式不建议使用,当文件太大是会超出内存容量的    public static void readFile_3() {        FileInputStream fis = null;        try {            fis = new FileInputStream("fos.txt");            byte[] bt = new byte[fis.available()];  //定义一个刚刚好的缓冲区,不用在循环            fis.read(bt);            System.out.println(new String(bt));        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fis != null)                try {                    fis.close();                } catch (IOException e) {                    e.printStackTrace();                }        }    }    // 第二种读取方式:使用数组读取      建议使用这个方法    public static void readFile_2() {        FileInputStream fis = null;        try {            fis = new FileInputStream("fos.txt");            int num = 0;            byte[] bt = new byte[1024];            while ((num = fis.read(bt)) != -1) {                System.out.println(new String(bt, 0, num));            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fis != null)                try {                    fis.close();                } catch (IOException e) {                    e.printStackTrace();                }        }    }    // 第一种读取方式:单个字节读取    public static void readFile_1() {        FileInputStream fis = null;        try {            fis = new FileInputStream("fos.txt");            int num = 0;            while ((num = fis.read()) != -1) {                System.out.println((char) num);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fis != null)                try {                    fis.close();                } catch (IOException e) {                    e.printStackTrace();                }        }    }    // 以字节流方式写入文本文件    public static void fileWrite() {        FileOutputStream fos = null;        try {            fos = new FileOutputStream("fos.txt");            fos.write("abcde".getBytes()); // 以byte数组方式        } catch (IOException e) {            e.printStackTrace();        } finally {            if (fos != null)                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }        }    }}</strong>
需求:将指定目录下的.java文件路径,全部写入到一个文本文件了,作文一个清单,(例如:遍历电影所在位置的列表) 
 例子5:
public class JavaFileList {    public static void main(String[] args) throws IOException {        File file = new File("D:\\JavaWeb\\workroomHeima\\Heima\\src\\day09_IO");        List<File> list = new ArrayList<File>();        fileToList(file,list);        System.out.println("listSize:"+list.size());                //用于存储.java绝对路径的文本文件        File dir = new File(file,"javalist.txt");        writeToFile(list, dir.toString());    }            //将指定目录下的.java文件放入list集合中    public static void fileToList(File file,List<File> list){        File[] files = file.listFiles();        for(File f : files){            if(f.isDirectory()){                fileToList(file,list);            }else{                if(f.getName().endsWith(".java")){                    list.add(f);                }            }        }    }        public static void writeToFile(List<File> list,String javaListFile)throws IOException{        BufferedWriter bufw = null;                try {            bufw = new BufferedWriter(new FileWriter(javaListFile));                        for(File file : list){                bufw.write(file.getAbsolutePath());                bufw.newLine();                bufw.flush();            }                    } catch (IOException e) {            e.printStackTrace();        }finally{            if(bufw != null)                try {                    bufw.close();                } catch (IOException e) {                    e.printStackTrace();                }        }            }}


需求:自定义自己的一个字节流缓冲区类
 例子6:
<strong>class MyBufferedInputStream {    private InputStream in;    private byte[] buf = new byte[1024*4];    private int pos = 0, count = 0;    public MyBufferedInputStream(InputStream in) {        this.in = in;    }    //一次读一个字节,从缓冲区(字节数组)获取。    public int myRead()throws IOException{        //通过in对象读取硬盘上数据,并存储buf中        if(count==0){            count = in.read(buf);            if(count<0)                return -1;            pos =0;            byte b= buf[pos];            count--;            pos++;            return b&255;    //防止-1出现        }        else if(count>0){            byte b= buf[pos];            count --;            pos++;            return b&0xff;  //防止-1出现        }        return -1;    }    public void myClose()throws IOException{        in.close();    }}</strong>

读取键盘录入。
System.out:对应的是标准输出设备,控制台
System.in :对应标准的输入设备:   键盘。

需求:
通过键盘录入数据
当录入一行数据后,就将该行数据进行打印
如果录入的数据是over   那么停止录入 
 例子6:
public class ReadIn {    public static void main(String[] args) {        InputStream in = System.in;        StringBuilder sb = new StringBuilder();        while(true){            try {                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());                }else                    sb.append((char)ch);            } catch (IOException e) {                e.printStackTrace();            }        }    }}


 需求:将指定目录下的文件和目录进行删除
 删除原理:
 在window中   删除目录从里面往外面删除
 既然是从里面往外面删除,就需要递归 
   例子7:
 
    public static void main(String[] args) {        File file = new File("D:\\新建文件夹");        deleteDir(file);    }    public static void deleteDir(File dir) {        File[] file = dir.listFiles();        for (File f1 : file) {            if (!f1.isHidden() && f1.isDirectory())                deleteDir(f1);            else                System.out.println(f1.getName() + "-----" + f1.delete());        }        System.out.println(dir.toString() + "_______" + dir.delete());    }}
需求:  将系统启动信息打印到一个文件中
例子8:




<strong>public class SystemInfo {    public static void main(String[] args) {        Properties prop = System.getProperties();   //Properties是Map集合的子类        try {            PrintStream ps = new PrintStream("SystemInfo.txt");  //创建流文件            prop.list(ps);      //将系统信息写入流文件中        } catch (FileNotFoundException e) {            e.printStackTrace();        }    }}</strong>

将字节流转换成字符流
 需求:
 通过键盘录入数据
 当录入一行数据后,就将该行数据进行打印
 如果录入的数据是over   那么停止录入需求:
 通过键盘录入数据
 当录入一行数据后,就将该行数据进行打印
 如果录入的数据是over   那么停止录入

例子9:  

public class TransStreamDemo {    public static void main(String[] args) throws IOException {        // 键盘录入对象//      InputStream in = System.in;//      // 将字节流对象转换成字符流对象,使用转换流 InputStreamReader//      InputStreamReader isr = new InputStreamReader(in);//      // 为了提高效率 将字符串进行缓冲区技术高效操作, 使用BufferedReader//      BufferedReader bufr = new BufferedReader(isr);        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));                //输出打印//      OutputStream out= System.out;//      OutputStreamWriter osw = new OutputStreamWriter(out);//      BufferedWriter bufw = new BufferedWriter(osw);        BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));                        String temp = null;        while ((temp = bufr.readLine()) != null) {            if (temp.equals("over"))                break;            bufw.write(temp.toUpperCase());            bufw.newLine();         //跨平台换行            bufw.flush();        }        bufr.close();        bufw.close();    }    //测试字节流转换成字符流    public static void trans_1() {        // 键盘录入对象        InputStream in = System.in;        // 将字节流对象转换成字符流对象,使用转换流 InputStreamReader        InputStreamReader isr = new InputStreamReader(in);        // 为了提高效率 将字符串进行缓冲区技术高效操作, 使用BufferedReader        BufferedReader bufr = null;        String temp = null;        try {            bufr = new BufferedReader(isr);            while ((temp = bufr.readLine()) != null) {                if (temp.equals("over"))                    break;                System.out.println(temp);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (bufr != null)                try {                    bufr.close();                } catch (IOException e) {                    e.printStackTrace();                }        }    }}


1.源:键盘录入

 2.目的:控制台

 2.需求:想把键盘录入的数据存入到一个文件中
 源:键盘
 目的:问价


3.需求:想要将一个文件的数据打印在控制台上
源:文件
目的:控制台

流操作的基本规律:
最痛苦的就是流对象有多个,不知道该用那一个

通过两个明确来完成

1.明确源和目的
源:输入流。InputStream  Reader
目的:输出流。OutputStream Writer
2.操作的数据是否是纯文本
是:字符流
不是:字节流
3.当体系明确后,在明确要使用那个具体的对象
通过设备类进行区分
源设备:内存,硬盘,键盘
目的设备:内存,硬盘,控制台
1.将一个文本文件中的数据存储到另外一个文件中,复制文件
源:因为是源,所以使用都读取流    InputStream  Reader
是不是操作文本文件。
是:这时就可以选择Reader
这样体系就明确了
明确设备:硬盘上的一个文件
Reader体系中可以操作文件的对象是: FileReader
是否需要提高效率:是! 加入Reader体系中的缓冲区: BufferedReader
BufferedReader bufr = new BufferedReader(new FileReader("a.txt"));
目的:OutputStream Writer
是否是纯文本
是:Writer
设备:硬盘一个文件
Writer体系中操作文件的对象是:FileWriter
是否需要提高效率:是! 加入Writer体系中的缓冲区: BufferedWriter
BufferedWriter bufw = new BufferedReader(new FileWriter("b.txt"))
练习:将一个图片文件中的数据存储到另一个文件中,复制文件

---------------------------------------------------
扩展知识,想要把录入的数据按照指定的编码表(utr-8) ,将数据存到文件中,
FileWriter是使用的默认编码表 GBK
但是存储时,需要键入指定编码表utf-8,而指定的编码表只有转换流可以指定
所以要使用的对象是OutputStreamWriter
而该转换流对象要接收一个字节输入流,而且还可以操作的文件的字节输入流  FileOutputStream
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d.txt"),"utf-8");
是否需提高效率?
是         BufferedWriter bufw = new BufferedWriter(osw);
所以,记住,转换流什么使用。   字符和字节之间的桥梁,通常,涉及到字符编码转换时}
需要用到转换流

例子10: 

public class TransSteamDemo2 {    public static void main(String[] args) throws IOException {        // 需求:将一个文本文件读取打印到控制台中        BufferedReader bufr = new BufferedReader(new InputStreamReader(                new FileInputStream("TransStreamDemo2.txt")));        // BufferedReader bufr = new BufferedReader(new        // InputStreamReader(System.in));        // 需求:想把键盘录入的数据存入到一个文件中        // BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new        // FileOutputStream("TransStreamDemo2.txt")));        BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(                System.out));        String temp = null;        while ((temp = bufr.readLine()) != null) {            if (temp.equals("over"))                break;            bufw.write(temp.toUpperCase());            bufw.newLine(); // 跨平台换行            bufw.flush();        }        bufr.close();        bufw.close();    }}

 将程序出现的异常打印到日志文件中

但,在真正的项目中,我们会使用到专门的日志工具Log4j

例子11:
public class ExceptionInfo {    public static void main(String[] args) {        try{        int[] arr = new int[2];        System.out.println(arr[3]);    //这里我们故意设置异常,然后try  catch一下        }catch (Exception e) {            Date d = new Date();            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            String s = df.format(d);                        try {                PrintStream ps = new PrintStream("exception.log");    //创建日志文件                ps.print(s+"    ");                System.setOut(ps);            } catch (FileNotFoundException e1) {                System.out.println("日志文件创建失败");            }            e.printStackTrace(System.out);   //将日志写入日志文件中        }    }}


需求:使用字节缓冲流技术复制一个Mp3文件 
例子12:



<strong>public class CopyMp3 {    public static void main(String[] args) {        long start = System.currentTimeMillis(); // 开始时间        mycopy();        long end = System.currentTimeMillis(); // 结束时间        System.out.println((end - start) + "毫秒");    }    // 使用自己定义的字节缓冲区    public static void mycopy() {        BufferedOutputStream bufos = null; // 写        MyBufferedInputStream bufis = null; // 读 自定义的缓冲区类        try {            bufos = new BufferedOutputStream(new FileOutputStream(                    "东京食种_copy01.mp3"));            bufis = new MyBufferedInputStream(new FileInputStream("东京食种.mp3"));            int num = 0;            while ((num = bufis.myRead()) != -1) {                bufos.write(num);            }        } catch (IOException e) {            System.out.println("读取文件资源错误");        } finally {            try {                if (bufos != null)                    bufos.close();            } catch (IOException e) {                System.out.println("关闭资源错误");            }            if (bufis != null)                try {                    bufis.myClose();                } catch (IOException e) {                    System.out.println("关闭资源错误");                }        }    }    public static void copy_1() {        BufferedOutputStream bufos = null; // 写        BufferedInputStream bufis = null; // 读        try {            bufos = new BufferedOutputStream(new FileOutputStream(                    "东京食种_copy.mp3"));            bufis = new BufferedInputStream(new FileInputStream("东京食种.mp3"));            byte[] bt = new byte[1024];            int num = 0;            while ((num = bufis.read(bt)) != -1) {                bufos.write(bt, 0, num);            }        } catch (IOException e) {            System.out.println("读取文件资源错误");        } finally {            try {                if (bufos != null)                    bufos.close();            } catch (IOException e) {                System.out.println("关闭资源错误");            }            if (bufis != null)                try {                    bufis.close();                } catch (IOException e) {                    System.out.println("关闭资源错误");                }        }    }}</strong>

 需求:复制一个图片

思路:
1.用字节流读取流对象和图片关联
2.用字节写入流对象创建一个图片文件,用于存储获取到的图片数据
3.通过循环读写,完成数据的存储
4.关闭资源
例子13:

public class CopyPic {    public static void main(String[] args) {        FileOutputStream fos = null; // 写入文件流        FileInputStream fis = null; // 读取文件流        try {            fos = new FileOutputStream("2.jpg");            fis = new FileInputStream("1.jpg");            byte[] bt = new byte[1024];            int num = 0;            while ((num = fis.read(bt)) != -1) {                fos.write(bt, 0, num);            }        } catch (IOException e) {            System.out.println("读写文件错误");        } finally {            try {                if (fos != null)                    fos.close();            } catch (IOException e) {                System.out.println("关闭文件流出错");            }                try {                    if(fis!=null)                    fis.close();                } catch (IOException e) {                    System.out.println("关闭文件流出错");                }        }    }}

 PrintWriter  向文本输出流打印对象的格式化表示形式)
向文本输出流打印对象的格式化表示形式。此类实现在 PrintStream 中的所有 print 方法。
它不包含用于写入原始字节的方法,对于这些字节,程序应该使用未编码的字节流进行写入 
PrintStream 类不同,如果启用了自动刷新,则只有在调用printlnprintfformat 的其中一个方法时才可能完成此操作,
而不是每当正好输出换行符时才完成。这些方法使用平台自有的行分隔符概念,而不是换行符 
 

构造函数可以接受的参数类型:
1.file对象,File
2.字符串类型。String
3.字节输出:OutputStream
4.字符输出流:Writer

需求:将手动输入的文本保存到一个a.txt文件中
例子14: 
public class PrintStreamDemo {    public static void main(String[] args)throws IOException {        BufferedReader  bufr = new BufferedReader(new InputStreamReader(System.in));        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();    }}


 
Properties集合  (一般用于操作配置文件,将文件中的键值对保存其中,Properties 继承于Hashtable
 
Properties 类表示了一个持久的属性集。
 
Properties 可保存在流中或从流中加载。
属性列表中每个键及其对应值都是一个字符串。
 
1.用一个流和info.txt文件关联
2.读取一行数据,将改行数据用“=”进行切割
3、等号左边作为键,右边作为值,存储到Properties集合中中

演示:如何将流中的数据存储到集合中
想要将info.txt中键值数据存到集合中进行操作 

例子15: 
public class PropertiesDemo {    public static void main(String[] args)throws IOException{//      setAndget();//      method_1();        loadDemo();    }        public static void loadDemo()throws IOException{        Properties pro = new Properties();        pro.load(new FileReader("info.txt"));        pro.setProperty("zhaoliu", "66");        FileOutputStream fos = new FileOutputStream("info.txt");        //用于重新添加元素之后刷入文件中        pro.store(fos, "hahah");        print(pro);        fos.close();    }        public static void method_1()throws IOException{        BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));        String line = null;        Properties pro = new Properties();        while((line=bufr.readLine()) != null){            String[] s = line.split("=");            pro.setProperty(s[0], s[1]);        }        print(pro);    }    // 设置和获取元素    public static void setAndget(){        Properties prop  = new Properties();                prop.setProperty("zhangsan", "30");        prop.setProperty("lisi", "35");                print("zhangsan  value:"+prop.getProperty("zhangsan"));                Set<String> names = prop.stringPropertyNames();        for(String s: names){            print(s+":"+prop.getProperty(s));        }                    }    private static void print(Object obj) {        System.out.println(obj);    }}


 RandomAccessFile类
 该类不是IO体系中的子类
 而是直接继承Object
 
 但是它是IO包中成员,因为它是具备读写功能
 额你不封装了一个数组,而且通过指针对数组的元素进行操作
 可以通过getFilePointer获取指针位置
 通过可以通过seek改变指针位置

其实完成读写的原理就是内部封装了字节输入流和输出流

通过构造函数可以看出,该类只能操作文件
而且操作文件还有模式:只读r,读写rw等

如果模式为只读r   不会创建文件,会去读取一个已存在文件,如果该文件不存在,则会出现异常
如果模式为rw   操作的文件不存在,会自动创建,如果存在则不会覆盖
 
例子16:
public class RandomAccessFileDemo {    public static void main(String[] args) throws IOException {//       testWrite();        testRead();    }    public static void testRead() throws IOException {        RandomAccessFile raf = new RandomAccessFile("Random.txt", "rw");        //调整对象中指针        raf.seek(8);        byte[] bt = new byte[4];        raf.read(bt);        String s =  new String(bt);        int age = raf.readInt();        print("name:" +s);        print("age:" + age);                //可以指定位置插入数据        raf.seek(22);        raf.write("赵柳".getBytes());        raf.writeInt(98);        raf.close();    }    public static void testWrite() throws IOException {        RandomAccessFile raf = new RandomAccessFile("Random.txt", "rw");        raf.write("李四".getBytes());        raf.writeInt(97);        raf.write("王五".getBytes());        raf.writeInt(99);        raf.close();    }    public static void print(Object obj) {        System.out.println(obj);    }}

 需求:用于记录应用程序运行次数。  如果使用次数移到,那么给出注册提示
很容以想到:计数器
可是该计数器定义在程序中,随着程序的运行而在内存中存在,并进行自增
可是随着该应用程序的退出,该计数器也在内存在消失
所以我们要建立一个配置文件  用于记录该软件的使用次数
该配置文件使用键值的形式
这样便于读取数据,并操作数据
键值对数据是map集合
数据是以文件形式存储,使用IO技术
配置文件可以实现应用程序数据的共享

例子17:  
 
public class RunConut {    public static void main(String[] args) throws IOException {        Properties pro = new Properties();        File file = new File("conut.ini");        if(!file.exists())            file.createNewFile();        pro.load(new  FileReader(file));        int count = 0;        String value = pro.getProperty("time");        if(value!=null){            count = Integer.parseInt(value);            if(count>=5){                System.out.println("您好,您已经使用软件超过5次,请注册付费之后使用!谢谢");                return;             }        }        count ++;        pro.setProperty("time",count+"");        pro.store(new FileOutputStream(file), "");    }}

SequenceInputStream表示其他输入流的逻辑串联。
它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,
接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止。 
 
需求 :将多个文本文件变成一个文件 (使用到Vector集合将文件连接)

  例子18:
 
public class SequenceDemo {    public static void main(String[] args) throws IOException {        Vector<FileInputStream> ve = new Vector<FileInputStream>();        ve.add(new FileInputStream("1.txt"));        ve.add(new FileInputStream("2.txt"));        ve.add(new FileInputStream("3.txt"));        Enumeration<FileInputStream> en = ve.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);        }        fos.close();        sis.close();    }}


 需求:将打文件切割成多个小文件,   然后再组装回去
 练习:将图片切割然后组装(当我们要发送大文件给别人s时,就需要到切割技术)

例子10:


public class SplitFile {    public static void main(String[] args) throws IOException{//      splitFile(); //  切割文件        merge();     //将切割之后的文件片重新组装    }    //组装功能    public static void merge() throws IOException{        ArrayList<FileInputStream> arr = new ArrayList<FileInputStream>();        for(int i = 1 ; i<=4 ; i++){            arr.add(new FileInputStream("东京食种"+i+".part"));        }        final Iterator<FileInputStream> it = arr.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("东京食种(123).mp3");        byte[] buf = new byte[1024*1024*3];        int len = 0;        while((len = sis.read(buf)) != -1){            fos.write(buf,0,len);            fos.flush();        }        fos.close();        sis.close();    }    //文件切片功能    public static void splitFile() throws IOException {        FileInputStream fis = new FileInputStream("东京食种.mp3");        FileOutputStream fos = null;        byte[] bt = new byte[1024 * 1024*3];        int len = 0;        int count = 1;        while((len=fis.read(bt)) != -1){            fos = new FileOutputStream("东京食种"+(count++)+".part");            fos.write(bt,0,len);            fos.close();        }        fis.close();    }}

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

例子20:   

public class EnodeDemo {    //这种二次转换会使用在服务器中    public static void main(String[] args) throws UnsupportedEncodingException {        String s = "你好";        byte[] bt = s.getBytes("GBK"); // 指定编码形式,可能不支持编码表,所以抛出异常信息        System.out.println(Arrays.toString(bt));// 使用Arrays工具类打印字节数组        String s1 = new String(bt, "ISO8859-1"); // 指定ISO8859-1解码        System.out.println("s1:" + s1);        byte[] bt1 = s1.getBytes("ISO8859-1");        System.out.println(Arrays.toString(bt1));// 使用Arrays工具类打印字节数组        String s2 = new String(bt1, "GBK"); // 指定ISO8859-1解码        System.out.println("s2:" + s2);    }}








0 0
原创粉丝点击