io流常见实例记录

前几天复习io流,写了一些入门实例,仅供记录参考


1. 文件操作

/**
 * 文件处理 File,包括:创建文件,创建目录,文件改名,递归打印目录下文件
 * @author wangchenlu
 * @time 2017年7月12日
 */
public class Tree {
    public static void main(String[] args) {
        String dirName = "e:/luxury/test";
        String fileName = "e:/luxury/test/test.mp3";
        createAllDirs(dirName);
        createMyFile(fileName);
        File file = new File(fileName);
        
        //文件后缀改为.txt的方法
        file.renameTo(new File("e:/luxury/test/" + file.getName().substring(0, file.getName().lastIndexOf('.'))+ ".txt"));
        System.out.println(file.length());
        
        // 打印当前目录
        if (args == null || args.length == 0) {
            displayFiles(new File("."), 0);
        } else {
            displayFiles(new File(args[0]), 0);
        }
    }
    /**
     * 递归打印目录下所有文件夹和文件
     * @return void
     * @author: wangchenlu
     */
    private static void displayFiles(File directory, int depth) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                for (int i = 0; i < depth - 1; ++i) {
                    System.out.print("|   ");
                }
                if (depth != 0) {
                    System.out.print("|-- ");
                }
                System.out.println(file.getName());
                if (file.isDirectory()) {
                    displayFiles(file, depth + 1);
                }
            }
        }
    }
    /**
     * 创建文件
     * @return void
     * @author: wangchenlu
     */
    private static void createMyFile(String fileName) {
        File file = new File(fileName);
        try {
            //不存在,创建文件并返回true;存在,返回false
            if (file.createNewFile()) {
                System.out.println("创建文件 " + file.toString() + " 成功");
            } else {
                System.out.println("文件 " + file.toString() + " 已存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static void createOneDir(String dirName) {
        //通过 创建目录的名字 创建
        File dir = new File(dirName);
        //mkdir()只能创建一级目录,即父目录必须存在
        if (dir.mkdir()) {
            System.out.println("创建目录 " + dir.toString() + " 成功");
        } else {
            System.out.println("创建目录 " + dir.toString() + " 失败");
        }
    }
    
    private static void createAllDirs(String dirName) {
      //通过 创建目录的名字 创建
        File dir = new File(dirName);
        //mkdirs()可以创建多级目录,中间不存在的父目录也可以创建出来
        //除mkdirs方法外,其他方法在创建文件和目录时,必须保证目标文件不存在,而且父目录存在,否则会创建失败
        if (dir.mkdirs()) {
            System.out.println("创建目录 " + dir.toString() + " 成功");
        } else {
            System.out.println("创建目录 " + dir.toString() + " 失败");
        }
    }
}


2. 字节、字符流操作

public class MyTest {
    public static void main(String[] args) {
        //copyFile("e:/luxury/test/test.txt", "e:/luxury/test/copy.txt");
        //countAll("e:/luxury/test/test.txt");
        countIt("e:/luxury/test/test.txt", "sa");
        
    }
    
    /**
     * 复制文件
     * @return void
     * @author: wangchenlu
     */
    public static void copyFile(String srcName, String destName) {
        File srcFile = new File(srcName);
        if(!srcFile.exists()) {
            System.out.println("oops! File " + srcName + " does not exit!");
        }
        File destFile = new File(destName);
        //先在try外面声明一下,并赋为null;才能在finally里关闭
        FileInputStream fis = null;
        FileOutputStream fos = null;
        //采用FileInputStream 适用于任何类型的文件,
        //但如果确定是文本文件,采用FileInputReader读取字符更高效
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            //初始化数组,用于存读入的文件数据
            byte[] tempByte = new byte[1024];
            //读取文件中的字节到数组中,默认每次读取数组长度1024个字节,也可以指定读取长度
            while ((fis.read(tempByte) != -1)) {
                fos.write(tempByte);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //io流一定要在finally里关闭!
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 统计文件中出现的字母、数字、空格个数及行数
     * @return void
     * @author: wangchenlu
     */
    public static void countAll(String fileName) {
        File file = new File(fileName);
        BufferedReader br = null;
        BufferedWriter bw = null;
        int letterNum = 0;
        int numNum = 0;
        int spaceNum = 0;
        int lineNum = 0;
        //因为是判断字符,所以用字符流Reader,使用缓冲BufferedReader效率更高
        try {
            //BufferedReader可以套接Reader接口,套接转换流InputStreamReader可以以字节流读取文件,转换成字符流
            //BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            
            //BufferedReader也可以套接FileReader,直接从文件中读字符流
            br = new BufferedReader(new FileReader(file));
            String read = br.readLine();
            while (read != null) {
                char[] charArray = read.toCharArray();
                for (int i = 0; i < charArray.length; i ++) {
                    if (Character.isLetter(charArray[i])) {
                        letterNum ++;
                    } else if (Character.isDigit(charArray[i])) {
                        numNum ++;
                    } else if (Character.isSpaceChar(charArray[i])) {
                        spaceNum ++;
                    }
                }
                lineNum ++;
                read = br.readLine();
            }
            String result = "字母:" + String.valueOf(letterNum) + " 数字:" + String.valueOf(numNum)
                + " 空格:" + String.valueOf(spaceNum) + " 总行数:" + String.valueOf(lineNum);
            System.out.println(result);
            bw = new BufferedWriter(new FileWriter(file, true));
            //几种写入换行的方法!
            //bw.newLine();
            //bw.write( System.lineSeparator() + result);
            bw.write( "\r\n" + result);//一定是/r/n,/n/r就不行。。。
            bw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 统计文档中某个字符(串)dest出现的次数
     * @return void
     * @author: wangchenlu
     */
    public static void countIt(String fileName, String dest) {
        File file = new File(fileName);
        int count = 0;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            
            //一种方法:用String类的自带方法进行统计
           /* 
            String line = br.readLine();
            while (line != null) {
                //从哪个index开始统计
                int index = 0;
                while (line.indexOf(dest, index) != -1) {
                    index = line.indexOf(dest, index) + dest.length();
                    count ++;
                    if (index > line.length()) {
                        break;
                    }
                }
                line = br.readLine();
            }
            */
            
            //另一种方法,创建一个StringBuilder存放所有从文档中读取的内容,然后对整个StringBuilder进行统计
            StringBuilder sb = new StringBuilder();
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                sb.append(line);
            }
            //借助正则表达式进行统计
            Pattern p = Pattern.compile(dest);
            Matcher m = p.matcher(sb);
            while (m.find()) {
                count ++;
            }
            
            
            System.out.println(count);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }

}



猜你喜欢

转载自blog.csdn.net/blacktal/article/details/75332998
今日推荐