No_16_0322 Java基础学习第二十二天

文档版本 开发工具 测试平台 工程名字 日期 作者 备注
V1.0 2016.03.22 lutianfei none

[TOC]


转换流出现的原因及思想

  • 由于字节流操作中文不是特别方便,所以,java就提供了转换流
  • 字符流 = 字节流 + 编码表

编码表

  • 字符及其对应的数值组成的一张表

常见编码表

  • 计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识别各个国家的文字。
  • ASCII:美国标准信息交换码。
    • 用一个字节的7位可以表示。
  • ISO8859-1:拉丁码表。欧洲码表
    • 用一个字节的8位表示。
  • GB2312:中国的中文编码表。
  • GBK:中国的中文编码表升级,融合了更多的中文文字符号。
  • GB18030:GBK的取代版本
  • BIG-5码 :通行于台湾、香港地区的一个繁体字编码方案,俗称“大五码”。
  • Unicode:国际标准码,融合了多种文字。
    • 所有文字都用两个字节来表示,Java语言使用的就是unicode
  • UTF-8:最多用三个字节来表示一个字符。
  • UTF-8不同,它定义了一种“区间规则”,这种规则可以和ASCII编码保持最大程度的兼容:
    • 它将Unicode编码为00000000-0000007F的字符,用单个字节来表示
    • 它将Unicode编码为00000080-000007FF的字符用两个字节表示
    • 它将Unicode编码为00000800-0000FFFF的字符用3字节表示

字符串中的编码问题

  • 编码

    • byte[] getBytes(String charsetName):使用指定的字符集合把字符串编码为字节数组
  • 解码

    • String(byte[] bytes, String charsetName):通过指定的字符集解码字节数组
  • 编码:把看得懂的变成看不懂的

    • String -- byte[]
  • 解码:把看不懂的变成看得懂的

    • byte[] -- String
public class StringDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "你好";

        // String -- byte[]
        byte[] bys = s.getBytes(); // [-60, -29, -70, -61]
        // byte[] bys = s.getBytes("GBK");// [-60, -29, -70, -61]
        // byte[] bys = s.getBytes("UTF-8");// [-28, -67, -96, -27, -91, -67]
        System.out.println(Arrays.toString(bys));
        
        // byte[] -- String
        String ss = new String(bys); // 你好
        // String ss = new String(bys, "GBK"); // 你好
        // String ss = new String(bys, "UTF-8"); // ???
        System.out.println(ss);
    }
}

转换流概述

  • OutputStreamWriter 字符输出流

    • OutputStreamWriter(OutputStream out):根据默认编码把字节流的数据转换为字符流
    • OutputStreamWriter(OutputStream out,String charsetName):根据指定编码把字节流数据转换为字符流
  • InputStreamReader 字符输入流

    • InputStreamReader(InputStream is):用默认的编码读取数据
    • InputStreamReader(InputStream is,String charsetName):用指定的编码读取数据

OutputStreamWriter写数据

  • OutputStreamWriter写数据方法
    • public void write(int c):写一个字符
    • public void write(char[] cbuf):写一个字符数组
    • public void write(char[] cbuf,int off,int len):写一个字符数组的一部分
    • public void write(String str):写一个字符串
    • public void write(String str,int off,int len):写一个字符串的一部分
public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        // 创建对象
        // OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
        // "osw.txt")); // 默认GBK
        // OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
        // "osw.txt"), "GBK"); // 指定GBK
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
                "osw.txt"), "UTF-8"); // 指定UTF-8
        // 写数据
        osw.write("中国");

        // 释放资源
        osw.close();
    }
}


字符流操作要注意的问题

  • flush()和close()的区别
    • A:close()关闭流对象,但是先刷新一次缓冲区。关闭之后,流对象不可以继续再使用了。
    • B:flush()仅仅刷新缓冲区,刷新之后,流对象还可以继续使用。
public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        // 创建对象
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
                "osw2.txt"));

        // 写数据
        // public void write(int c):写一个字符
        // osw.write('a');
        // osw.write(97);
        // 为什么数据没有进去呢?
        // 原因是:字符 = 2字节
        // 文件中数据存储的基本单位是字节。
        // void flush()

        // public void write(char[] cbuf):写一个字符数组
        // char[] chs = {'a','b','c','d','e'};
        // osw.write(chs);

        // public void write(char[] cbuf,int off,int len):写一个字符数组的一部分
        // osw.write(chs,1,3);

        // public void write(String str):写一个字符串
        // osw.write("我爱林青霞");

        // public void write(String str,int off,int len):写一个字符串的一部分
        osw.write("我爱林青霞", 2, 3);

        // 刷新缓冲区
        osw.flush();
        // osw.write("我爱林青霞", 2, 3);

        // 释放资源
        osw.close();
        // java.io.IOException: Stream closed
        // osw.write("我爱林青霞", 2, 3);
    }
}


InputStreamReader读数据

  • 读数据方法
    • int read():一次读取一个字符
    • int read(char[] chs):一次读取一个字符数组
public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        // 创建对象
        // InputStreamReader isr = new InputStreamReader(new FileInputStream(
        // "osw.txt"));

        // InputStreamReader isr = new InputStreamReader(new FileInputStream(
        // "osw.txt"), "GBK");

        InputStreamReader isr = new InputStreamReader(new FileInputStream(
                "osw.txt"), "UTF-8");

        // 读取数据
        // 一次读取一个字符
        int ch = 0;
        while ((ch = isr.read()) != -1) {
            System.out.print((char) ch);
        }

        // 释放资源
        isr.close();
    }
}



public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        // 创建对象
        InputStreamReader isr = new InputStreamReader(new FileInputStream(
                "StringDemo.java"));

        // 一次读取一个字符
        // int ch = 0;
        // while ((ch = isr.read()) != -1) {
        // System.out.print((char) ch);
        // }

        // 一次读取一个字符数组
        char[] chs = new char[1024];
        int len = 0;
        while ((len = isr.read(chs)) != -1) {
            System.out.print(new String(chs, 0, len));
        }

        // 释放资源
        isr.close();
    }
}


字符流复制文本文件

  • 把当前项目目录下的a.txt内容复制到当前项目目录下的b.txt中
/*
 * 需求:把当前项目目录下的a.txt内容复制到当前项目目录下的b.txt中
 * 
 * 数据源:
 *         a.txt -- 读取数据 -- 字符转换流 -- InputStreamReader
 * 目的地:
 *         b.txt -- 写出数据 -- 字符转换流 -- OutputStreamWriter
 */
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        // 封装数据源
        InputStreamReader isr = new InputStreamReader(new FileInputStream(
                "a.txt"));
        // 封装目的地
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
                "b.txt"));

        // 读写数据
        // 方式1
        // int ch = 0;
        // while ((ch = isr.read()) != -1) {
        // osw.write(ch);
        // }

        // 方式2
        char[] chs = new char[1024];
        int len = 0;
        while ((len = isr.read(chs)) != -1) {
            osw.write(chs, 0, len);
            // osw.flush();
        }

        // 释放资源
        osw.close();
        isr.close();
    }
}


  • 把c:\a.txt内容复制到d:\b.txt中

转换流的简化写法

  • 转换流的名字比较长,而我们常见的操作都是按照本地默认编码实现的,所以,为了简化我们的书写,转换流提供了对应的子类。

  • FileWriter写数据

  • FileReader读取数据

  • OutputStreamWriter = FileOutputStream + 编码表(GBK)

    • FileWriter = FileOutputStream + 编码表(GBK)
  • InputStreamReader = FileInputStream + 编码表(GBK)

    • FileReader = FileInputStream + 编码表(GBK)
/*
 * 由于我们常见的操作都是使用本地默认编码,所以,不用指定编码。
 * 而转换流的名称有点长,所以,Java就提供了其子类供我们使用。
 * OutputStreamWriter = FileOutputStream + 编码表(GBK)
 
 * 需求:把当前项目目录下的a.txt内容复制到当前项目目录下的b.txt中
 * 
 * 数据源:
 *         a.txt -- 读取数据 -- 字符转换流 -- InputStreamReader -- FileReader
 * 目的地:
 *         b.txt -- 写出数据 -- 字符转换流 -- OutputStreamWriter -- FileWriter
 */
public class CopyFileDemo2 {
    public static void main(String[] args) throws IOException {
        // 封装数据源
        FileReader fr = new FileReader("a.txt");
        // 封装目的地
        FileWriter fw = new FileWriter("b.txt");

        // 一次一个字符
        // int ch = 0;
        // while ((ch = fr.read()) != -1) {
        // fw.write(ch);
        // }

        // 一次一个字符数组
        char[] chs = new char[1024];
        int len = 0;
        while ((len = fr.read(chs)) != -1) {
            fw.write(chs, 0, len);
            fw.flush();
        }

        // 释放资源
        fw.close();
        fr.close();
    }
}


字符缓冲流

  • 字符流为了高效读写,也提供了对应的字符缓冲流。
    • BufferedWriter:字符缓冲输出流
    • BufferedReader:字符缓冲输入流
BufferedWriter:字符缓冲输出流
  • 将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
  • 可以指定缓冲区的大小,或者接受默认的大小。在大多数情况下,默认值就足够大了。
public class BufferedWriterDemo {
    public static void main(String[] args) throws IOException {
        // BufferedWriter(Writer out)
        // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
        // new FileOutputStream("bw.txt")));

        BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

        bw.write("hello");
        bw.write("world");
        bw.write("java");
        bw.flush();

        bw.close();
    }
}


BufferedReader
  • 从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
  • 可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        // 创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("bw.txt"));

        // 方式1
        // int ch = 0;
        // while ((ch = br.read()) != -1) {
        // System.out.print((char) ch);
        // }

        // 方式2
        char[] chs = new char[1024];
        int len = 0;
        while ((len = br.read(chs)) != -1) {
            System.out.print(new String(chs, 0, len));
        }

        // 释放资源
        br.close();
    }
}


  • 文本复制例子
/*
 * 需求:把当前项目目录下的a.txt内容复制到当前项目目录下的b.txt中
 * 
 * 数据源:
 *         a.txt -- 读取数据 -- 字符转换流 -- InputStreamReader -- FileReader -- BufferedReader
 * 目的地:
 *         b.txt -- 写出数据 -- 字符转换流 -- OutputStreamWriter -- FileWriter -- BufferedWriter
 */
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        // 封装数据源
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        // 封装目的地
        BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));

        // 两种方式其中的一种一次读写一个字符数组
        char[] chs = new char[1024];
        int len = 0;
        while ((len = br.read(chs)) != -1) {
            bw.write(chs, 0, len);
            bw.flush();
        }

        // 释放资源
        bw.close();
        br.close();
    }
}


字符缓冲流的特殊方法

  • BufferedWriter:
    • public void newLine():根据系统来决定换行符
  • BufferedReader:
    • public String readLine():一次读取一行数据
      • 包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回null

public class BufferedDemo {
    public static void main(String[] args) throws IOException {
        // write();
        read();
    }

    private static void read() throws IOException {
        // 创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("bw2.txt"));

        // 最终版代码
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        
        //释放资源
        br.close();
    }

    private static void write() throws IOException {
        // 创建字符缓冲输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("bw2.txt"));
        for (int x = 0; x < 10; x++) {
            bw.write("hello" + x);
            // bw.write("\r\n");
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }

}


  • 字符缓冲流特殊功能复制文本文件)(必会)
/*
 * 需求:把当前项目目录下的a.txt内容复制到当前项目目录下的b.txt中
 * 
 * 数据源:
 *         a.txt -- 读取数据 -- 字符转换流 -- InputStreamReader -- FileReader -- BufferedReader
 * 目的地:
 *         b.txt -- 写出数据 -- 字符转换流 -- OutputStreamWriter -- FileWriter -- BufferedWriter
 */
public class CopyFileDemo2 {
    public static void main(String[] args) throws IOException {
        // 封装数据源
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        // 封装目的地
        BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));

        // 读写数据
        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        // 释放资源
        bw.close();
        br.close();
    }
}


IO流小结

  • 字节流
    • 字节输入流
    • 字节输出流
  • 字符流
    • 字符输入流
    • 字符输出流

IO流练习

  • 复制文本文件
/*
 * 复制文本文件
 * 
 * 分析:
 *         而字符流有5种方式,所以做这个题目我们有5种方式。推荐掌握第5种。
 * 数据源:
 *         c:\\a.txt -- FileReader -- BufferdReader
 * 目的地:
 *         d:\\b.txt -- FileWriter -- BufferedWriter
 */
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        String srcString = "c:\\a.txt";
        String destString = "d:\\b.txt";
        // method1(srcString, destString);
        // method2(srcString, destString);
        // method3(srcString, destString);
        // method4(srcString, destString);
        method5(srcString, destString);
    }

    // 字符缓冲流一次读写一个字符串
    private static void method5(String srcString, String destString)
            throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(srcString));
        BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        bw.close();
        br.close();
    }

    // 字符缓冲流一次读写一个字符数组
    private static void method4(String srcString, String destString)
            throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(srcString));
        BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

        char[] chs = new char[1024];
        int len = 0;
        while ((len = br.read(chs)) != -1) {
            bw.write(chs, 0, len);
        }

        bw.close();
        br.close();
    }

    // 字符缓冲流一次读写一个字符
    private static void method3(String srcString, String destString)
            throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(srcString));
        BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

        int ch = 0;
        while ((ch = br.read()) != -1) {
            bw.write(ch);
        }

        bw.close();
        br.close();
    }

    // 基本字符流一次读写一个字符数组
    private static void method2(String srcString, String destString)
            throws IOException {
        FileReader fr = new FileReader(srcString);
        FileWriter fw = new FileWriter(destString);

        char[] chs = new char[1024];
        int len = 0;
        while ((len = fr.read(chs)) != -1) {
            fw.write(chs, 0, len);
        }

        fw.close();
        fr.close();
    }

    // 基本字符流一次读写一个字符
    private static void method1(String srcString, String destString)
            throws IOException {
        FileReader fr = new FileReader(srcString);
        FileWriter fw = new FileWriter(destString);

        int ch = 0;
        while ((ch = fr.read()) != -1) {
            fw.write(ch);
        }

        fw.close();
        fr.close();
    }
}


  • 复制图片
/*
 * 复制图片
 * 
 * 分析:
 *         复制数据,如果我们知道用记事本打开并能够读懂,就用字符流,否则用字节流。
 *         通过该原理,我们知道我们应该采用字节流。
 *         而字节流有4种方式,所以做这个题目我们有4种方式。推荐掌握第4种。
 * 
 * 数据源:
 *         c:\\a.jpg -- FileInputStream -- BufferedInputStream
 * 目的地:
 *         d:\\b.jpg -- FileOutputStream -- BufferedOutputStream
 */
public class CopyImageDemo {
    public static void main(String[] args) throws IOException {
        // 使用字符串作为路径
        // String srcString = "c:\\a.jpg";
        // String destString = "d:\\b.jpg";
        // 使用File对象做为参数
        File srcFile = new File("c:\\a.jpg");
        File destFile = new File("d:\\b.jpg");

        // method1(srcFile, destFile);
        // method2(srcFile, destFile);
        // method3(srcFile, destFile);
        method4(srcFile, destFile);
    }

    // 字节缓冲流一次读写一个字节数组
    private static void method4(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(destFile));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }

        bos.close();
        bis.close();
    }

    // 字节缓冲流一次读写一个字节
    private static void method3(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(destFile));

        int by = 0;
        while ((by = bis.read()) != -1) {
            bos.write(by);
        }

        bos.close();
        bis.close();
    }

    // 基本字节流一次读写一个字节数组
    private static void method2(File srcFile, File destFile) throws IOException {
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
        }

        fos.close();
        fis.close();
    }

    // 基本字节流一次读写一个字节
    private static void method1(File srcFile, File destFile) throws IOException {
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);

        int by = 0;
        while ((by = fis.read()) != -1) {
            fos.write(by);
        }

        fos.close();
        fis.close();
    }
}


  • 把ArrayList集合中的字符串数据存储到文本文件
/*
 * 需求:把ArrayList集合中的字符串数据存储到文本文件
 * 
 * 分析:
 * 通过题目的意思我们可以知道如下的一些内容,
 * ArrayList集合里存储的是字符串。
 * 遍历ArrayList集合,把数据获取到。
 * 然后存储到文本文件中。
 * 文本文件说明使用字符流。
 * 
 * 数据源:
 *         ArrayList<String> -- 遍历得到每一个字符串数据
 * 目的地:
 *         a.txt -- FileWriter -- BufferedWriter
 */
public class ArrayListToFileDemo {
    public static void main(String[] args) throws IOException {
        // 封装数据源(创建集合对象)
        ArrayList<String> array = new ArrayList<String>();
        array.add("hello");
        array.add("world");
        array.add("java");

        // 封装目的地
        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));

        // 遍历集合
        for (String s : array) {
            // 写数据
            bw.write(s);
            bw.newLine();
            bw.flush();
        }

        // 释放资源
        bw.close();
    }
}


  • 从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合
/*
 * 需求:从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合
 * 
 * 分析:
 *         通过题目的意思我们可以知道如下的一些内容,
 *             数据源是一个文本文件。
 *             目的地是一个集合。
 *             而且元素是字符串。
 * 
 * 数据源:
 *         b.txt -- FileReader -- BufferedReader
 * 目的地:
 *         ArrayList<String>
 */
public class FileToArrayListDemo {
    public static void main(String[] args) throws IOException {
        // 封装数据源
        BufferedReader br = new BufferedReader(new FileReader("b.txt"));
        // 封装目的地(创建集合对象)
        ArrayList<String> array = new ArrayList<String>();

        // 读取数据存储到集合中
        String line = null;
        while ((line = br.readLine()) != null) {
            array.add(line);
        }

        // 释放资源
        br.close();

        // 遍历集合
        for (String s : array) {
            System.out.println(s);
        }
    }
}


  • 随机获取文本中的名字
/*
 * 需求:我有一个文本文件中存储了几个名称,请大家写一个程序实现随机获取一个人的名字。
 * 
 * 分析:
 *         A:把文本文件中的数据存储到集合中
 *         B:随机产生一个索引
 *         C:根据该索引获取一个值
 */
public class GetName {
    public static void main(String[] args) throws IOException {
        // 把文本文件中的数据存储到集合中
        BufferedReader br = new BufferedReader(new FileReader("b.txt"));
        ArrayList<String> array = new ArrayList<String>();
        String line = null;
        while ((line = br.readLine()) != null) {
            array.add(line);
        }
        br.close();

        // 随机产生一个索引
        Random r = new Random();
        int index = r.nextInt(array.size());

        // 根据该索引获取一个值
        String name = array.get(index);
        System.out.println("该幸运者是:" + name);
    }
}


  • 复制单极文件夹
/*
 * 需求:复制单极文件夹
 * 
 * 数据源:e:\\demo
 * 目的地:e:\\test
 * 
 * 分析:
 *         A:封装目录
 *         B:获取该目录下的所有文本的File数组
 *         C:遍历该File数组,得到每一个File对象
 *         D:把该File进行复制
 */
public class CopyFolderDemo {
    public static void main(String[] args) throws IOException {
        // 封装目录
        File srcFolder = new File("e:\\demo");
        // 封装目的地
        File destFolder = new File("e:\\test");
        // 如果目的地文件夹不存在,就创建
        if (!destFolder.exists()) {
            destFolder.mkdir();
        }

        // 获取该目录下的所有文本的File数组
        File[] fileArray = srcFolder.listFiles();

        // 遍历该File数组,得到每一个File对象
        for (File file : fileArray) {
            // System.out.println(file);
            // 数据源:e:\\demo\\e.mp3
            // 目的地:e:\\test\\e.mp3
            String name = file.getName(); // e.mp3
            File newFile = new File(destFolder, name); // e:\\test\\e.mp3

            copyFile(file, newFile);
        }
    }

    private static void copyFile(File file, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(newFile));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }

        bos.close();
        bis.close();
    }
}


  • 复制单极文件夹中指定文件并修改文件名称
/*
 * 需求:复制指定目录下的指定文件,并修改后缀名。
 * 指定的文件是:.java文件。
 * 指定的后缀名是:.jad
 * 指定的目录是:jad
 * 
 * 数据源:e:\\java\\A.java
 * 目的地:e:\\jad\\A.jad
 * 
 * 分析:
 *         A:封装目录
 *         B:获取该目录下的java文件的File数组
 *         C:遍历该File数组,得到每一个File对象
 *         D:把该File进行复制
 *         E:在目的地目录下改名
 */
public class CopyFolderDemo {
    public static void main(String[] args) throws IOException {
        // 封装目录
        File srcFolder = new File("e:\\java");
        // 封装目的地
        File destFolder = new File("e:\\jad");
        // 如果目的地目录不存在,就创建
        if (!destFolder.exists()) {
            destFolder.mkdir();
        }

        // 获取该目录下的java文件的File数组
        File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return new File(dir, name).isFile() && name.endsWith(".java");
            }
        });

        // 遍历该File数组,得到每一个File对象
        for (File file : fileArray) {
            // System.out.println(file);
            // 数据源:e:\java\DataTypeDemo.java
            // 目的地:e:\\jad\DataTypeDemo.java
            String name = file.getName();
            File newFile = new File(destFolder, name);
            copyFile(file, newFile);
        }

        // 在目的地目录下改名
        File[] destFileArray = destFolder.listFiles();
        for (File destFile : destFileArray) {
            // System.out.println(destFile);
            // e:\jad\DataTypeDemo.java
            // e:\\jad\\DataTypeDemo.jad
            String name =destFile.getName(); //DataTypeDemo.java
            String newName = name.replace(".java", ".jad");//DataTypeDemo.jad
            
            File newFile = new File(destFolder,newName);
            destFile.renameTo(newFile);
        }
    }

    private static void copyFile(File file, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(newFile));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }

        bos.close();
        bis.close();
    }
}


  • 复制多极文件夹
/*
 * 需求:复制多极文件夹
 * 
 * 数据源:E:\JavaSE\day21\code\demos
 * 目的地:E:\\
 * 
 * 分析:
 *         A:封装数据源File
 *         B:封装目的地File
 *         C:判断该File是文件夹还是文件
 *             a:是文件夹
 *                 就在目的地目录下创建该文件夹
 *                 获取该File对象下的所有文件或者文件夹File对象
 *                 遍历得到每一个File对象
 *                 回到C
 *             b:是文件
 *                 就复制(字节流)
 */
public class CopyFoldersDemo {
    public static void main(String[] args) throws IOException {
        // 封装数据源File
        File srcFile = new File("E:\\JavaSE\\day21\\code\\demos");
        // 封装目的地File
        File destFile = new File("E:\\");

        // 复制文件夹的功能
        copyFolder(srcFile, destFile);
    }

    private static void copyFolder(File srcFile, File destFile)
            throws IOException {
        // 判断该File是文件夹还是文件
        if (srcFile.isDirectory()) {
            // 文件夹
            File newFolder = new File(destFile, srcFile.getName());
            newFolder.mkdir();

            // 获取该File对象下的所有文件或者文件夹File对象
            File[] fileArray = srcFile.listFiles();
            for (File file : fileArray) {
                copyFolder(file, newFolder);
            }
        } else {
            // 文件
            File newFile = new File(destFile, srcFile.getName());
            copyFile(srcFile, newFile);
        }
    }

    private static void copyFile(File srcFile, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(newFile));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }

        bos.close();
        bis.close();
    }
}


  • 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
/*
 * 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
 * 
 * 分析:
 *         A:创建学生类
 *         B:创建集合对象
 *             TreeSet<Student>
 *         C:键盘录入学生信息存储到集合
 *         D:遍历集合,把数据写到文本文件
 */
public class StudentDemo {
    public static void main(String[] args) throws IOException {
        // 创建集合对象
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s2.getSum() - s1.getSum();
                int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
                int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3;
                int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName())
                        : num4;
                return num5;
            }
        });

        // 键盘录入学生信息存储到集合
        for (int x = 1; x <= 5; x++) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请录入第" + x + "个的学习信息");
            System.out.println("姓名:");
            String name = sc.nextLine();
            System.out.println("语文成绩:");
            int chinese = sc.nextInt();
            System.out.println("数学成绩:");
            int math = sc.nextInt();
            System.out.println("英语成绩:");
            int english = sc.nextInt();

            // 创建学生对象
            Student s = new Student();
            s.setName(name);
            s.setChinese(chinese);
            s.setMath(math);
            s.setEnglish(english);

            // 把学生信息添加到集合
            ts.add(s);
        }

        // 遍历集合,把数据写到文本文件
        BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
        bw.write("学生信息如下:");
        bw.newLine();
        bw.flush();
        bw.write("姓名,语文成绩,数学成绩,英语成绩");
        bw.newLine();
        bw.flush();
        for (Student s : ts) {
            StringBuilder sb = new StringBuilder();
            sb.append(s.getName()).append(",").append(s.getChinese())
                    .append(",").append(s.getMath()).append(",")
                    .append(s.getEnglish());
            bw.write(sb.toString());
            bw.newLine();
            bw.flush();
        }
        // 释放资源
        bw.close();
        System.out.println("学习信息存储完毕");
    }
}


  • 已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
    • 请编写程序读取数据内容,把数据排序后写入ss.txt中。
/*
 * 已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
 * 请编写程序读取数据内容,把数据排序后写入ss.txt中。
 * 
 * 分析:
 *         A:把s.txt这个文件给做出来
 *         B:读取该文件的内容,存储到一个字符串中
 *         C:把字符串转换为字符数组
 *         D:对字符数组进行排序
 *         E:把排序后的字符数组转换为字符串
 *         F:把字符串再次写入ss.txt中
 */
public class StringDemo {
    public static void main(String[] args) throws IOException {
        // 读取该文件的内容,存储到一个字符串中
        BufferedReader br = new BufferedReader(new FileReader("s.txt"));
        String line = br.readLine();
        br.close();

        // 把字符串转换为字符数组
        char[] chs = line.toCharArray();

        // 对字符数组进行排序
        Arrays.sort(chs);

        // 把排序后的字符数组转换为字符串
        String s = new String(chs);

        // 把字符串再次写入ss.txt中
        BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt"));
        bw.write(s);
        bw.newLine();
        bw.flush();

        bw.close();
    }
}


  • 用Reader模拟BufferedReader的readLine()功能
/*
 * 用Reader模拟BufferedReader的readLine()功能
 * 
 * readLine():一次读取一行,根据换行符判断是否结束,只返回内容,不返回换行符
 */
public class MyBufferedReader {
    private Reader r;

    public MyBufferedReader(Reader r) {
        this.r = r;
    }

    /*
     * 思考:写一个方法,返回值是一个字符串。
     */
    public String readLine() throws IOException {
        /*
         * 我要返回一个字符串,我该怎么办呢? 我们必须去看看r对象能够读取什么东西呢? 两个读取方法,一次读取一个字符或者一次读取一个字符数组
         * 那么,我们要返回一个字符串,用哪个方法比较好呢? 我们很容易想到字符数组比较好,但是问题来了,就是这个数组的长度是多长呢?
         * 根本就没有办法定义数组的长度,你定义多长都不合适。 所以,只能选择一次读取一个字符。
         * 但是呢,这种方式的时候,我们再读取下一个字符的时候,上一个字符就丢失了 所以,我们又应该定义一个临时存储空间把读取过的字符给存储起来。
         * 这个用谁比较合适呢?数组,集合,字符串缓冲区三个可供选择。
         * 经过简单的分析,最终选择使用字符串缓冲区对象。并且使用的是StringBuilder
         */
        StringBuilder sb = new StringBuilder();

        // 做这个读取最麻烦的是判断结束,但是在结束之前应该是一直读取,直到-1
        
        
        /*
        hello
        world
        java    
        
        104101108108111
        119111114108100
        1069711897
         */
        
        int ch = 0;
        while ((ch = r.read()) != -1) { //104,101,108,108,111
            if (ch == '\r') {
                continue;
            }

            if (ch == '\n') {
                return sb.toString(); //hello
            } else {
                sb.append((char)ch); //hello
            }
        }

        // 为了防止数据丢失,判断sb的长度不能大于0
        if (sb.length() > 0) {
            return sb.toString();
        }

        return null;
    }

    /*
     * 先写一个关闭方法
     */
    public void close() throws IOException {
        this.r.close();
    }
}


  • 自定义类模拟LineNumberReader的特有功能
    • 获取每次读取数据的行号
public class MyLineNumberReaderTest {
    public static void main(String[] args) throws IOException {
        // MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader(
        // "my.txt"));

        MyLineNumberReader2 mlnr = new MyLineNumberReader2(new FileReader(
                "my.txt"));

        // mlnr.setLineNumber(10);

        // System.out.println(mlnr.getLineNumber());
        // System.out.println(mlnr.getLineNumber());
        // System.out.println(mlnr.getLineNumber());

        String line = null;
        while ((line = mlnr.readLine()) != null) {
            System.out.println(mlnr.getLineNumber() + ":" + line);
        }

        mlnr.close();
    }
}





public class MyLineNumberReader2 extends MyBufferedReader {
    private Reader r;

    private int lineNumber = 0;

    public MyLineNumberReader2(Reader r) {
        super(r);
    }

    public int getLineNumber() {
        return lineNumber;
    }

    public void setLineNumber(int lineNumber) {
        this.lineNumber = lineNumber;
    }

    @Override
    public String readLine() throws IOException {
        lineNumber++;
        return super.readLine();
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 一、流的概念和作用。 流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输...
    布鲁斯不吐丝阅读 9,950评论 2 95
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,293评论 18 399
  • [TOC] 异常 异常:异常就是Java程序在运行过程中出现的 错误 。 异常由来:问题也是现实生活中一个具体事务...
    lutianfei阅读 419评论 0 1
  • 1 IONo18 1.1IO框架 【 IO:Input Output 在程序运行的过程中,可能需要对一些设备进...
    征程_Journey阅读 906评论 0 1
  • 今天要给大家分享的就是“笨蛋+白痴+弱智” 哇~有眼光的朋友已经看出破绽了对吗?哈哈没错今天的主题是笨蛋+白痴+弱...
    筑梦安琪阅读 584评论 0 0