码迷,mamicode.com
首页 > 编程语言 > 详细

Java基础3——IO

时间:2015-12-12 15:22:46      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

1、File类

构造函数

/*
 * 我们要想实现IO的操作,就必须知道硬盘上文件的表现形式。
 * 而Java就提供了一个类File供我们使用。
 * 
 * File:文件和目录(文件夹)路径名的抽象表示形式
 * 构造方法:
 *         File(String pathname):根据一个路径得到File对象
 *         File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
 *         File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象
 */
public class FileDemo {
    public static void main(String[] args) {
        // File(String pathname):根据一个路径得到File对象
        // 把e:\\demo\\a.txt封装成一个File对象
        File file = new File("E:\\demo\\a.txt");

        // File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
        File file2 = new File("E:\\demo", "a.txt");

        // File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象
        File file3 = new File("e:\\demo");
        File file4 = new File(file3, "a.txt");

        // 以上三种方式其实效果一样
    }
}

创建文件或文件夹

/*
 *创建功能:
 *public boolean createNewFile():创建文件 如果存在这样的文件,就不创建了
 *public boolean mkdir():创建文件夹 如果存在这样的文件夹,就不创建了
 *public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来
 *
 *骑白马的不一定是王子,可能是班长。
 *注意:你到底要创建文件还是文件夹,你最清楚,方法不要调错了。
 */
public class FileDemo {
    public static void main(String[] args) throws IOException {
        // 需求:我要在e盘目录下创建一个文件夹demo
        File file = new File("e:\\demo");
        System.out.println("mkdir:" + file.mkdir());

        // 需求:我要在e盘目录demo下创建一个文件a.txt
        File file2 = new File("e:\\demo\\a.txt");
        System.out.println("createNewFile:" + file2.createNewFile());

        // 需求:我要在e盘目录test下创建一个文件b.txt
        // Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
        // 注意:要想在某个目录下创建内容,该目录首先必须存在。
        // File file3 = new File("e:\\test\\b.txt");
        // System.out.println("createNewFile:" + file3.createNewFile());

        // 需求:我要在e盘目录test下创建aaa目录
        // File file4 = new File("e:\\test\\aaa");
        // System.out.println("mkdir:" + file4.mkdir());

        // File file5 = new File("e:\\test");
        // File file6 = new File("e:\\test\\aaa");
        // System.out.println("mkdir:" + file5.mkdir());
        // System.out.println("mkdir:" + file6.mkdir());

        // 其实我们有更简单的方法
        File file7 = new File("e:\\aaa\\bbb\\ccc\\ddd");
        System.out.println("mkdirs:" + file7.mkdirs());

        // 会创建出a.txt这样一个文件夹,而不会创建a.txt文本文件
        File file8 = new File("e:\\liuyi\\a.txt");
        System.out.println("mkdirs:" + file8.mkdirs());
    }
}

删除文件或文件夹

/*
 * 删除功能:public boolean delete()
 * 
 * 注意:
 *         A:如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下。
 *         B:Java中的删除不走回收站。
 *         C:要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹
 */
public class FileDemo {
    public static void main(String[] args) throws IOException {
        // 我不小心写成这个样子了
        File file = new File("a.txt");
        System.out.println("createNewFile:" + file.createNewFile());

        // 继续玩几个
        File file2 = new File("aaa\\bbb\\ccc");
        System.out.println("mkdirs:" + file2.mkdirs());

        // 删除功能:我要删除a.txt这个文件
        File file3 = new File("a.txt");
        System.out.println("delete:" + file3.delete());

        // 删除功能:我要删除ccc这个文件夹
        File file4 = new File("aaa\\bbb\\ccc");
        System.out.println("delete:" + file4.delete());

        // 删除功能:我要删除aaa文件夹
        // File file5 = new File("aaa");
        // System.out.println("delete:" + file5.delete());

        File file6 = new File("aaa\\bbb");
        File file7 = new File("aaa");
        System.out.println("delete:" + file6.delete());
        System.out.println("delete:" + file7.delete());
    }
}

重命名

/*
 * 重命名功能:public boolean renameTo(File dest)
 *         如果路径名相同,就是改名。
 *         如果路径名不同,就是改名并剪切。
 * 
 * 路径以盘符开始:绝对路径    c:\\a.txt
 * 路径不以盘符开始:相对路径    a.txt
 */
public class FileDemo {
    public static void main(String[] args) {
        // 创建一个文件对象
        // File file = new File("林青霞.jpg");
        // // 需求:我要修改这个文件的名称为"东方不败.jpg"
        // File newFile = new File("东方不败.jpg");
        // System.out.println("renameTo:" + file.renameTo(newFile));

        File file2 = new File("东方不败.jpg");
        File newFile2 = new File("e:\\林青霞.jpg");
        System.out.println("renameTo:" + file2.renameTo(newFile2));
    }
}

判断功能

/*
 * 判断功能:
 * public boolean isDirectory():判断是否是目录
 * public boolean isFile():判断是否是文件
 * public boolean exists():判断是否存在
 * public boolean canRead():判断是否可读
 * public boolean canWrite():判断是否可写
 * public boolean isHidden():判断是否隐藏
 */
public class FileDemo {
    public static void main(String[] args) {
        // 创建文件对象
        File file = new File("a.txt");

        System.out.println("isDirectory:" + file.isDirectory());// false
        System.out.println("isFile:" + file.isFile());// true
        System.out.println("exists:" + file.exists());// true
        System.out.println("canRead:" + file.canRead());// true
        System.out.println("canWrite:" + file.canWrite());// true
        System.out.println("isHidden:" + file.isHidden());// false
    }
}

获取功能

/*
 * 获取功能:
 * public String getAbsolutePath():获取绝对路径
 * public String getPath():获取相对路径
 * public String getName():获取名称
 * public long length():获取长度。字节数
 * public long lastModified():获取最后一次的修改时间,毫秒值
 */
public class FileDemo {
    public static void main(String[] args) {
        // 创建文件对象
        File file = new File("demo\\test.txt");

        System.out.println("getAbsolutePath:" + file.getAbsolutePath());
        System.out.println("getPath:" + file.getPath());
        System.out.println("getName:" + file.getName());
        System.out.println("length:" + file.length());
        System.out.println("lastModified:" + file.lastModified());

        // 1416471971031
        Date d = new Date(1416471971031L);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = sdf.format(d);
        System.out.println(s);
    }
}

获取路径

/*
 * 获取功能:
 * public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
 * public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
 */
public class FileDemo {
    public static void main(String[] args) {
        File file = new File("e:\\");

        String[] strArray = file.list();
        for (String s : strArray) {
            System.out.println(s);
        }
        File[] fileArray = file.listFiles();
        for (File f : fileArray) {
            System.out.println(f.getName());
        }
    }
}

判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称 

/*
 * 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
 * 
 * 分析:
 *         A:封装e判断目录
 *         B:获取该目录下所有文件或者文件夹的File数组
 *         C:遍历该File数组,得到每一个File对象,然后判断
 *         D:是否是文件
 *             是:继续判断是否以.jpg结尾
 *                 是:就输出该文件名称
 *                 否:不搭理它
 *             否:不搭理它
 */
public class FileDemo {
    public static void main(String[] args) {
        // 封装e判断目录
        File file = new File("e:\\");

        // 获取该目录下所有文件或者文件夹的File数组
        File[] fileArray = file.listFiles();

        // 遍历该File数组,得到每一个File对象,然后判断
        for (File f : fileArray) {
            // 是否是文件
            if (f.isFile()) {
                // 继续判断是否以.jpg结尾
                if (f.getName().endsWith(".jpg")) {
                    // 就输出该文件名称
                    System.out.println(f.getName());
                }
            }
        }
    }
}

以上问题的另一种思路(用文件名过滤器接口改造)

/*
 * 获取的时候就已经是满足条件的了,然后输出即可。
 * 
 * 要想实现这个效果,就必须学习一个接口:文件名称过滤器
 * public String[] list(FilenameFilter filter)
 * public File[] listFiles(FilenameFilter filter)
 */
public class FileDemo2 {
    public static void main(String[] args) {
        // 封装e判断目录
        File file = new File("e:\\");

        // 获取该目录下所有文件或者文件夹的String数组
        // public String[] list(FilenameFilter filter)
        String[] strArray = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {// 到底把这个文件或者文件夹的名称加不加到数组中,取决于这里的返回值是true还是false
                return new File(dir, name).isFile() && name.endsWith(".jpg");
            }
        });

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

递归删除带内容的目录

/*
 * 分析:
 *         A:封装目录
 *         B:获取该目录下的所有文件或者文件夹的File数组
 *         C:遍历该File数组,得到每一个File对象
 *         D:判断该File对象是否是文件夹
 *             是:回到B
 *             否:就删除
 */
public class FileDeleteDemo {
    public static void main(String[] args) {
        // 封装目录
        File srcFolder = new File("demo");
        // 递归实现
        deleteFolder(srcFolder);
    }

    private static void deleteFolder(File srcFolder) {
        // 获取该目录下的所有文件或者文件夹的File数组
        File[] fileArray = srcFolder.listFiles();

        if (fileArray != null) {
            // 遍历该File数组,得到每一个File对象
            for (File file : fileArray) {
                // 判断该File对象是否是文件夹
                if (file.isDirectory()) {
                    deleteFolder(file);
                } else {
                    System.out.println(file.getName() + "---" + file.delete());
                }
            }
            System.out.println(srcFolder.getName() + "---" + srcFolder.delete());
        }
    }
}

把E:\JavaSE目录下所有的java结尾的文件的绝对路径给输出在控制台

public FilePathDemo{
    public static void main(String[] args){
        File f=new File("E:\\demo");
        getAllJavaFilePaths(f);
    }
    private static void getAllJavaFilePaths(File srcFolder){
        File[] files=srcFolder.listFiles();
        for(File file:files){
            if(file.isDirectory()){
                getAllJavaFilePaths(file);
            }else{
                if(file.getName().endsWith(".java")){
                    System.out.println(file.getAbsolutePath());
                }
            }
        }
    }
}

InputStream/OutputStream是字节流的顶层的两个抽象类,Reader/Writer是字符流的顶层的两个抽象类

输入流即读取,输出流即写进

在流的类名中有这样一个规律:每种基类的子类都是以父类名作为后缀名

2、FileInputStream/FileOutputStream BufferedInputStream/BufferedOutputStream

写入FileOutputStream

/*
 * 需求:我要往一个文本文件中输入一句话:"hello,io"
 * 
 * 分析:
 *         A:这个操作最好是采用字符流来做,但是呢,字符流是在字节流之后才出现的,所以,今天我先讲解字节流如何操作。
 *         B:由于我是要往文件中写一句话,所以我们要采用字节输出流。
 * 
 * 通过上面的分析后我们知道要使用:OutputStream
 * 查看FileOutputStream的构造方法:
 *         FileOutputStream(File file) 
 *        FileOutputStream(String name)
 *
 * 字节输出流操作步骤:
 *         A:创建字节输出流对象
 *         B:写数据
 *         C:释放资源
 */
public class FileOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        // 创建字节输出流对象
        FileOutputStream fos = new FileOutputStream("fos.txt");
        /*
         * 创建字节输出流对象了做了几件事情:
         * A:调用系统功能去创建文件
         * B:创建fos对象
         * C:把fos对象指向这个文件
         */
        
        //写数据
        fos.write("hello,IO".getBytes());
        fos.write("java".getBytes());
        
        //释放资源
        //关闭此文件输出流并释放与此流有关的所有系统资源。
        fos.close();
    }
}
/*
 * 字节输出流操作步骤:
 * A:创建字节输出流对象
 * B:调用write()方法
 * C:释放资源
 * 
 * public void write(int b):写一个字节
 * public void write(byte[] b):写一个字节数组
 * public void write(byte[] b,int off,int len):写一个字节数组的一部分
 */
public class FileOutputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("fos2.txt");

        // 调用write()方法
        //fos.write(97); //97 -- 底层二进制数据    -- 通过记事本打开 -- 找97对应的字符值 -- a
        // fos.write(57);
        // fos.write(55);
        
        //public void write(byte[] b):写一个字节数组
        byte[] bys={97,98,99,100,101};
        fos.write(bys);
        
        //public void write(byte[] b,int off,int len):写一个字节数组的一部分
        fos.write(bys,1,3);
        
        //释放资源
        fos.close();
    }
}
/*
 * 如何实现数据的换行?
 *         为什么现在没有换行呢?因为你值写了字节数据,并没有写入换行符号。
 *         如何实现呢?写入换行符号即可呗。
 *         刚才我们看到了有写文本文件打开是可以的,通过windows自带的那个不行,为什么呢?
 *         因为不同的系统针对不同的换行符号识别是不一样的?
 *         windows:\r\n
 *         linux:\n
 *         Mac:\r
 *         而一些常见的个高级记事本,是可以识别任意换行符号的。
 * 
 * 如何实现数据的追加写入?
 *         用构造方法带第二个参数是true的情况即可
 */
public class FileOutputStreamDemo3 {
    public static void main(String[] args) throws IOException {
        // 创建字节输出流对象
        // FileOutputStream fos = new FileOutputStream("fos3.txt");
        // 创建一个向具有指定 name 的文件中写入数据的输出文件流。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。
        FileOutputStream fos = new FileOutputStream("fos3.txt", true);

        // 写数据
        for (int x = 0; x < 10; x++) {
            fos.write(("hello" + x).getBytes());
            fos.write("\r\n".getBytes());
        }

        // 释放资源
        fos.close();
    }
}
/*
 * 加入异常处理的字节输出流操作
 */
public class FileOutputStreamDemo4 {
    public static void main(String[] args) {// 改进版
        // 为了在finally里面能够看到该对象就必须定义到外面,为了访问不出问题,还必须给初始化值
        FileOutputStream fos = null;
        try {
            // fos = new FileOutputStream("z:\\fos4.txt");
            fos = new FileOutputStream("fos4.txt");
            fos.write("java".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 如果fos不是null,才需要close()
            if (fos != null) {
                // 为了保证close()一定会执行,就放到这里了
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

读取——FileInputStream

/*
 * 字节输入流操作步骤:
 * A:创建字节输入流对象
 * B:调用read()方法读取数据,并把数据显示在控制台
 * C:释放资源
 * 
 * 读取数据的方式:
 * A:int read():一次读取一个字节
 * B:int read(byte[] b):一次读取一个字节数组
 */
public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("FileOutputStreamDemo.java");
        int by = 0;
        // 读取,赋值,判断
        while ((by = fis.read()) != -1) {
            System.out.print((char) by);
        }

        // 释放资源
        fis.close();
    }
}
/*
 * 一次读取一个字节数组:int read(byte[] b)
 * 返回值其实是实际读取的字节个数。
 */
public class FileInputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        // 创建字节输入流对象
        FileInputStream fis = new FileInputStream("FileOutputStreamDemo.java");// 数组的长度一般是1024或者1024的整数倍
        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = fis.read(bys)) != -1) {
            System.out.print(new String(bys, 0, len));
        }

        // 释放资源
        fis.close();
    }
}
/*
 * 计算机是如何识别什么时候该把两个字节转换为一个中文呢?
 * 在计算机中中文的存储分两个字节:
 *         第一个字节肯定是负数。
 *         第二个字节常见的是负数,可能有正数。但是没影响。
 */
public class StringDemo {
    public static void main(String[] args) {
        // String s = "abcde";
        // // [97, 98, 99, 100, 101]

        String s = "我爱你中国";
        // [-50, -46, -80, -82, -60, -29, -42, -48, -71, -6]

        byte[] bys = s.getBytes();
        System.out.println(Arrays.toString(bys));
    }
}
/*
 * 复制文本文件。
 * 
 * 数据源:从哪里来
 * a.txt    --    读取数据    --    FileInputStream    
 * 
 * 目的地:到哪里去
 * b.txt    --    写数据        --    FileOutputStream
 * 
 * java.io.FileNotFoundException: a.txt (系统找不到指定的文件。)
 * 
 * 这一次复制中文没有出现任何问题,为什么呢?
 * 上一次我们出现问题的原因在于我们每次获取到一个字节数据,就把该字节数据转换为了字符数据,然后输出到控制台。
 * 而这一次呢?确实通过IO流读取数据,写到文本文件,你读取一个字节,我就写入一个字节,你没有做任何的转换。
 * 它会自己做转换。
 */
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        // 封装数据源
        FileInputStream fis = new FileInputStream("a.txt");
        // 封装目的地
        FileOutputStream fos = new FileOutputStream("b.txt");

        int by = 0;
     // 此处还可以读取字节数组
     // byte[] bys = new byte[1024];
     // while(by = fis.read())
        while ((by = fis.read()) != -1) {
            fos.write(by);
        }

        // 释放资源(先关谁都行)
        fos.close();
        fis.close();
    }
}

BufferedInputStream

/*
 * 注意:虽然我们有两种方式可以读取,但是,请注意,这两种方式针对同一个对象在一个代码中只能使用一个。
 */
public class BufferedInputStreamDemo {
    public static void main(String[] args) throws IOException {
        // BufferedInputStream(InputStream in)
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                "bos.txt"));

        // 读取数据
        // int by = 0;
        // while ((by = bis.read()) != -1) {
        // System.out.print((char) by);
        // }
        // System.out.println("---------");

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
            System.out.print(new String(bys, 0, len));
        }

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

BufferedOutputStream 

/*
 * 通过定义数组的方式确实比以前一次读取一个字节的方式快很多,所以,看来有一个缓冲区还是非常好的。
 * 既然是这样的话,那么,java开始在设计的时候,它也考虑到了这个问题,就专门提供了带缓冲区的字节类。
 * 这种类被称为:缓冲区类(高效类)
 * 写数据:BufferedOutputStream
 * 读数据:BufferedInputStream
 * 
 * 构造方法可以指定缓冲区的大小,但是我们一般用不上,因为默认缓冲区大小就足够了。
 * 
 * 为什么不传递一个具体的文件或者文件路径,而是传递一个OutputStream对象呢?
 * 原因很简单,字节缓冲区流仅仅提供缓冲区,为高效而设计的。但是呢,真正的读写操作还得靠基本的流对象实现。
 */
public class BufferedOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        // BufferedOutputStream(OutputStream out)
        // FileOutputStream fos = new FileOutputStream("bos.txt");
        // BufferedOutputStream bos = new BufferedOutputStream(fos);
        // 简单写法
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("bos.txt"));

        // 写数据
        bos.write("hello".getBytes());

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

字节流操作中文不是很方便,所以产生了字符流

字符流=字节流+码表

UTF-8最多用三个字节表示一个字符

字符串的编解码

/*
 * String(byte[] bytes, String charsetName):通过指定的字符集解码字节数组
 * byte[] getBytes(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);
    }
}

InputStreamReader/OutputStreamWriter

/*
* InputStreamReader构造方法 * InputStreamReader(InputStream is):用默认的编码读取数据 * InputStreamReader(InputStream is,String charsetName):用指定的编码读取数据 */ 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(); } }
/*
 * OutputStreamWriter(OutputStream out):根据默认编码把字节流的数据转换为字符流
 * OutputStreamWriter(OutputStream out,String charsetName):根据指定编码把字节流数据转换为字符流
 * 把字节流转换为字符流。
 * 字符流 = 字节流 +编码表。
 */
public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        // 创建对象
        // OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
        // "osw.txt")); // 使用默认的编码格式
        // 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();
    }
}
/*
 * OutputStreamWriter的方法:
 * public void write(int c):写一个字符
 * public void write(char[] cbuf):写一个字符数组
 * public void write(char[] cbuf,int start,int len):写一个字符数组的一部分
 * public void write(String str):写一个字符串
 * public void write(String str,int start,int len):写一个字符串的一部分
 * 
 * 面试题:close()和flush()的区别?
 * 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):写一个字符 事实上这个方法往进传一个整型值和传一个字符都是一样的,即传入‘a‘和97是一样的
        // osw.write(‘a‘);
        // osw.write(97);
        // 为什么数据没有进去呢?
        // 原因是:字符 = 2字节
        // 文件中数据存储的基本单位是字节,osw.write(‘a‘)事实上是先将‘a‘写入缓冲区,要想真正写入文件,需要我们手动调用flush刷新一下// 写一个字符数组
        // char[] chs = {‘a‘,‘b‘,‘c‘,‘d‘,‘e‘};
        // osw.write(chs);

        // 写一个字符数组的一部分
        // 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();// 释放资源 事实上close的作用是先刷新缓冲区后关闭流对象,一旦关闭,流对象就不可以再继续使用了,而flush之后还可以再往进写数据
        osw.close();
    }
}

FileReader/FileWriter

/*
 * 由于我们常见的操作都是使用本地默认编码,所以,不用指定编码。
 * 而转换流的名称有点长,所以,Java就提供了其子类供我们使用。
 * OutputStreamWriter = FileOutputStream + 编码表(GBK)
 * FileWriter = FileOutputStream + 编码表(GBK)
 * 
 * InputStreamReader = FileInputStream + 编码表(GBK)
 * FileReader = FileInputStream + 编码表(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();
    }
}

BufferedReader/BufferedWriter

/*
 * 字符缓冲流的特殊方法:
 * 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"));

        // public String readLine():一次读取一行数据
        // String line = br.readLine();
        // System.out.println(line);
        // line = br.readLine();
        // System.out.println(line);
     // 其实BufferedReader也可以按照字符数组的方式读取
     // char[] chs = new char[1024];
     // int len = 0;
     // while((len=chs.read(chs)) != -1){
     // System.out.println(new String(chs,0,len));
     // }
// 最终版代码 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();
    }
}

对于复制数据的操作,如果我们知道用记事本打开并能够读懂,就用字符流,否则用字节流

通过该原理,我们知道我们应该采用字符流更方便一些

复制文本文件(共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种方法)

数据源:
  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();
    }
}

 

Java基础3——IO

标签:

原文地址:http://www.cnblogs.com/zhaohuiziwo901/p/5021321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!