JAVA IO/NIO相关操作单元测试示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xzpdskll/article/details/81813809
package com.imp4m.testAll;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.util.StopWatch;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * java nio、io相关操作
 * @author 10589
 * @date 2016/10/16
 * @time 14:19
 */
public class testAll {

    /**
     * java io SystemIn相关操作
     * @author skl
     * @date 2018年8月17日11:09:18
     */
    public static void javaIoOfSystemInTest(){
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String rtn = "";
        AtomicInteger atomicInteger = new AtomicInteger();
        do{
            try {
                rtn = bufferedReader.readLine();
                try {
                    Integer.parseInt(rtn);
                    System.out.println("echo:"+(Integer.valueOf(rtn)*3)+" 行号:"+atomicInteger.incrementAndGet());
                } catch (NumberFormatException e) {
                    System.out.println("错误:"+e);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }while (!rtn.equals("end"));

        System.out.println("系统退出!");
    }

    /**
     * java io 相关操作
     * @author skl
     * @date 2018年8月17日11:09:18
     */
    public static void javaIoOfFileTest(){
        /**
         * 字符类型的流输入输出操作
         */
        //readerAndWriterTest();

        /**
         * 字节类型的流输入输出操作、字节数组流类型的操作
         */
        //fileByteStreamOperate();

        /**
         * 随机访问
         * 1.支持只访问文件的部分内容
         * 2.可以向已存在的文件后追加内容
         */
        //randomAccessFileTest();

        /**
         * 数据类型的流操作
         */
        //dataInputOutputStreamTest();


        /**对象序列化*/
        //ObjectInputOutStreamTest();
    }

    /**
     * @desc 对象序列化
     * @author xlosy_skl
     * @date 2018年8月18日12:49:20
     */
    private static void ObjectInputOutStreamTest() {


        /**将Person对象序列化到文件*/
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:"+File.separator+"object.txt"));
            objectOutputStream.writeObject(new Person("1","sunkeliang","man",12));
        } catch (IOException e) {
            e.printStackTrace();
        }


        /**从文件反序列化Person对象到内存*/
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:"+File.separator+"object.txt"));
            Person person = (Person) in.readObject();
            System.out.println(person);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @desc 数据类型的流操作
     * @author xlosy_skl
     * @date 2018年8月18日11:10:45
     */
    private static void dataInputOutputStreamTest(){
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;
        try {
            //创建一个临时的文件
            dataOutputStream = new DataOutputStream(new FileOutputStream("d:"+File.separator+"dataInOutStream.txt"));
            String name[] = {"衣服","裤子","内衣"};
            float price[] = {12f,33f,32f};
            int num[] = {1,2,3};
            for (int i = 0; i <name.length; i++) {
                dataOutputStream.writeChars(name[i]);
                dataOutputStream.writeChar('\t');
                dataOutputStream.writeFloat(price[i]);
                dataOutputStream.writeChar('\t');
                dataOutputStream.writeInt(num[i]);
                dataOutputStream.writeChar('\n');
            }
            dataOutputStream.close();

            dataInputStream = new DataInputStream(new FileInputStream("d:"+File.separator+"dataInOutStream.txt"));
            String nameTemp = null;//名称
            float priceTemp  = 0f;
            int number  = 0;
            char c = 0;
            char tempName[] = null;
            int len = 0;
            while (true){
                tempName = new char[200];
                len = 0;
                while ((c=dataInputStream.readChar())!='\t'){
                    tempName[len] = c;
                    len++;
                }
                nameTemp = new String(tempName,0,len);
                priceTemp = dataInputStream.readFloat();
                dataInputStream.readChar();
                number =  dataInputStream.readInt();
                dataInputStream.readChar();

                System.out.println("名称:"+nameTemp);
                System.out.println("价格:"+priceTemp);
                System.out.println("数量:"+number);
            }
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }finally {
            if(dataOutputStream!=null){
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(dataInputStream!=null){
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @desc
     *  随机访问
     * 1.支持只访问文件的部分内容
     * 2.可以向已存在的文件后追加内容
     * @author xlosy_skl
     * @date 2018年8月18日11:09:43
     */
    private static void randomAccessFileTest() {
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile("D:"+ File.separator+"优秀网站网址.txt","rw");
            String s ;
            while ((s = randomAccessFile.readLine())!=null){
                byte[] bytes = s.getBytes("ISO-8859-1");
                System.out.println(new String(bytes, "utf-8"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @desc 字节类型的流输入输出操作
     * @author xlosy_skl
     * @date 2018年8月17日18:50:12
     */
    private static void fileByteStreamOperate(){
        StopWatch stopWatch = new StopWatch("字节类型输入输出操作");
        stopWatch.start("字节写入文件");
        BufferedInputStream bufferedInputStream = null;
        try {
            bufferedInputStream =new BufferedInputStream(new FileInputStream("D:"+ File.separator+"优秀网站网址.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder();
        try {
            if(bufferedInputStream!=null){
                byte bytes[] = new byte[1024];
                while (bufferedInputStream.read(bytes)!=-1){
                    stringBuilder.append(new String(bytes,"utf-8"));
                }
                System.out.println(stringBuilder.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bufferedInputStream!=null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        stopWatch.stop();
        stopWatch.start("字节输出文件");
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("D:"+ File.separator+"2.txt");
            /*if(fileOutputStream!=null){
                try {
                    fileOutputStream.write(stringBuilder.toString().getBytes("utf-8"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        stopWatch.stop();

        stopWatch.start("打印流输出文件");
        PrintStream printStream = new PrintStream(fileOutputStream, true);
        printStream.println(stringBuilder.toString());
        stopWatch.stop();


        stopWatch.start("字节数组流写入文件");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stringBuilder.toString().getBytes());
        int available = byteArrayInputStream.available();
        int result;
        while ((result = byteArrayInputStream.read())!=-1){
            System.out.print(Character.valueOf((char) result));
        }
        try {
            bufferedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bufferedInputStream!=null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        stopWatch.stop();

        stopWatch.start("字节数组流输出到文件");

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            byteArrayOutputStream.write(stringBuilder.toString().getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("D:"+ File.separator+"3.txt"));
            byteArrayOutputStream.writeTo(bufferedOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bufferedOutputStream!=null){
                try {
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        stopWatch.stop();
        System.out.println("markSupported:"+byteArrayInputStream.markSupported());
        System.out.println("available:"+available);
        System.out.println(stopWatch.prettyPrint());
    }


    /**
     * @desc 字符类型的输入输出操作
     * @author xlosy_skl
     * @date 2018年8月17日18:26:09
     */
    private static void readerAndWriterTest() {
        StopWatch stopWatch = new StopWatch("字符类型输入输出操作");
        stopWatch.start("读取文件");
        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            reader = new BufferedReader(new FileReader("D:"+ File.separator+"优秀网站网址.txt"));
            String str;
            while ((str = reader.readLine())!=null){
                stringBuilder.append(str+"\r\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(reader!=null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        stopWatch.stop();
        System.out.println(stringBuilder);
        stopWatch.start("写入文件");
        BufferedWriter fileWriter = null;
        try {
            fileWriter = new BufferedWriter(new FileWriter("D:"+File.separator+"1.txt"));
            String s = stringBuilder.toString();
            fileWriter.write(new String(s.getBytes("utf-8"),
                    "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileWriter!=null){
                    fileWriter.flush();
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }


    /**
     * 重写String的equals方法
     * @param str1
     * @param str2
     * @return
     */
    public static Boolean myEquals(String str1,String str2){
        /**
         * 1、不用验证是否是String的实例,验证是否为空
         */
        if(str1 == str2){
            return true;
        }

        /**
         * 2.判断是否为null
         */
        if(str1==null || str2==null){
            return false;
        }
        /**
         * 3.判断长度是否相等
         */
        if(str1.length() == str2.length()){
            char[] chars1 = str1.toCharArray();
            char[] chars2 = str2.toCharArray();
            int i  = 0;
            for (char c:chars1) {
                if(c != chars2[i]){
                    return false;
                }
                i++;
            }
            return true;
        }
        return false;
    }


    /**
     * @desc Nio操作
     * @author xlosy_skl
     * @date 2018年8月17日18:26:09
     */
    private static void nioCopyFileTest() throws IOException {

        /**基本方式*/
        /*FileChannel channel = new FileInputStream("D:" + File.separator + "1.txt").getChannel();
        FileChannel channel2 = new FileOutputStream("D:" + File.separator + "6.txt").getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (channel.read(byteBuffer)!=-1){
            byteBuffer.flip();
            channel2.write(byteBuffer);
            byteBuffer.clear();
        }
        channel.close();
        channel2.close();*/


        /**使用randomAccessFile方式,缓冲区映射的方式*/
        /*RandomAccessFile inf = new RandomAccessFile("D:"+File.separator+"优秀网站网址.txt","r");
        RandomAccessFile outf = new RandomAccessFile("D:"+File.separator+"7.txt","rw");

        FileChannel fInC = inf.getChannel();
        FileChannel fOutC = outf.getChannel();
        long size = fInC.size();
        MappedByteBuffer mapInf = fInC.map(FileChannel.MapMode.READ_ONLY, 0, size);
        MappedByteBuffer mapOutf = fOutC.map(FileChannel.MapMode.READ_WRITE, 0, size);
        for (int i = 0; i < size; i++) {
            mapOutf.put(mapInf.get());
        }
        fInC.close();
        fOutC.close();
        inf.close();
        outf.close();*/


        /**使用Path Paths工具类*/
        /*Path p = Paths.get("d://1.txt");
        List<String> strings = Files.readAllLines(p, Charset.forName("utf-8"));
        for (String str :strings) {
            System.out.println(str);
        }*/
        /*Path path = Paths.get("D://idea2016.1注册码.txt");
        Path pathTarget = Paths.get("D://安装包//破解软件集idea2016.1注册码.txt");
        Files.deleteIfExists(path);
        Files.move(pathTarget,path,StandardCopyOption.REPLACE_EXISTING);//如果存在则进行覆盖操作*/
    }

    /**
     * @desc File类操作测试
     * @author xlosy_skl
     * @date 2018年8月18日20:38:50
     */
    private static void fileClassOperateTest() throws IOException {
        File file = new File("D:"+File.separator+"安装包"+File.separator+"破解软件集"+File.separator+"");

        /**访问文件*/
        System.out.println("文件名:"+file.getName());
        System.out.println("绝对路径:"+file.getAbsolutePath());
        System.out.println("相对路径:"+file.getPath());
        System.out.println("标准路径:"+file.getCanonicalPath());
        System.out.println("绝对文件:"+file.getAbsoluteFile());
        System.out.println("上一级:"+file.getParent());
        System.out.println("上一级目录名称:"+ getParentName(file));

        /**文件检测*/
        System.out.println("文件是否存在:"+(file.exists()?"存在":"不存在"));
        System.out.println("文件是否可写:"+(file.canWrite()?"可写":"不可写"));
        System.out.println("文件是否可读:"+(file.canRead()?"可读":"不可读"));
        System.out.println("是否是文件:"+(file.isFile()?"是":"否"));
        System.out.println("是否是目录:"+(file.isDirectory()?"是":"否"));

        /**常规信息*/
        System.out.println("最后更改时间:"+ DateFormatUtils.format(new Date(file.lastModified()),"yyyy-MM-dd HH:mm:ss"));
        System.out.println("文件大小:"+ file.length()+"字节");


        /**文件操作*/
        //file.renameTo(new File("D:"+File.separator+"安装包"+File.separator+"破解软件集"+File.separator+"idea2016.1注册码.txt"));//重命名
        //file.createNewFile();//创建文件
        //file.delete();//删除文件,需要文件存在不然会报错
        //file.mkdir();//创建单级目录
        //file.mkdirs();//创建多级目录
        /*String[] list = file.list();
        for (int i = 0; i < list.length; i++) {
            System.out.println(list[i]);
        }*///获取当前目录下的子目录名称
        /*File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i]);
        }*///获取当前目录下的子文件

        /**复制目录下的所有文件到指定目录下*/
        copyDirectory("D:"+File.separator+"360安全浏览器下载","D:"+File.separator+"sun");
    }

    private static String getParentName(File file) {
        return file.getPath().substring(file.getPath().lastIndexOf(File.separator)+1,file.getPath().length());
    }

    /**
     * @desc 业务:复制目录下的所有文件到指定目录下
     * @author xlosy_skl
     * @date
     */
    private static boolean copyDirectory(String sourceDirectory,String targerDirectory) {
        File sourceDirectoryPath = new File(sourceDirectory);
        File targerDirectoryPath = new File(targerDirectory);
        if(!sourceDirectoryPath.exists()){
            return false;
        }
        try {
            recursionCopyDirectory(sourceDirectoryPath,targerDirectoryPath);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 业务:复制目录下的所有文件到指定目录下
     * 递归复制目录文件
     * @param sourceDirectory
     * @param targerDirectory
     */
    private static void recursionCopyDirectory(File sourceDirectory, File targerDirectory){
        File[] files = sourceDirectory.listFiles();
        for (int i = 0; i < files.length; i++) {
            if(files[i].isDirectory()){
                String parentName = getParentName(files[i]);
                File tempTargerDirectory = new File(targerDirectory.getPath()+File.separator+parentName);
                recursionCopyDirectory(files[i],tempTargerDirectory);
            }else{
                if(!targerDirectory.exists()){
                    targerDirectory.mkdirs();
                }
                try {
                    FileUtils.copyFile(files[i],new File(targerDirectory.getPath()+File.separator+files[i].getName()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String args[]) throws IOException {

        /**java多线程*/
        //threadTest();

        /**集合框架*/
        //setFramework();

        /**java io System.in为流的相关操作*/
        //javaIoOfSystemInTest();

        /**java io 文件相关操作*/
        //javaIoOfFileTest();

        /**重写String的equals方法*/
        //System.out.println(myEquals(null,new String("ab1")));

        /**java nio*/
        //nioCopyFileTest();

        /**File类操作测试*/
        //fileClassOperateTest();
    }
}

猜你喜欢

转载自blog.csdn.net/xzpdskll/article/details/81813809