Java -- 文件压缩及线程Demo

File代表文件和文件夹
JDk 1.4版引入了一套新的I/O系统称之为NIO
NIO - Non-blocking I/O - 非阻塞式I/O
Buffer - 缓冲区
Channel - 通道
CharSet - 字符集
Java 7 以后I/O(NIO.2)中添加了操作文件和路径的工具类
Files - 操作文件的工具类
Paths - 操作路径的工具类

public class Test01 {

    public static void main(String[] args) {
        File f = new File("abc.txt");
        System.out.println(f.getAbsolutePath());//获得绝对路径
        File f1 = new File("c:/windows");
        if (f1.isDirectory()) {//判断f1是不是文件夹
            String[] strs = f1.list();
            for (String temp : strs) {
                System.out.println(temp);
            }
        }
    }
}
文件的压缩
  • Eclipse生成Jar文件步骤:
    1.在eclipse中选择你要导出的类或者package,右击,选择Export子选项
    2.在弹出的对话框中,选择java文件---选择JAR file
    3.在JAR file后面的文本框中选择你要生成的jar包的位置以及名字
    4.Finnish
public class Test02 {

    public static void main(String[] args) {
        for(int i = 0; i < 5; i++){
            System.out.println(MyUtil.generateVC(4));
        }
    }
}
将文件压缩
  • GZipInputStream - 读取单个压缩文件 - 解压缩
  • GZipOutputStream - 压缩单个文件 - 压缩
  • ZipOutputStream - 将多个文件压缩成一个文件
  • ZipInputStream - 读取压缩文件还原成多个文件
public class Test03 {

    /**
     * 文件压缩
     * @param args
     */
    public static void main(String[] args) {
        
        try (OutputStream out = new FileOutputStream("c:/Users/apple/Desktop/test.zip")){
            //给压缩文件添加冗余校验码 - 用于验证压缩文件的正确性和完整性的附加数据
            //   - Adler32  - CRC32 两种校验码算法
            CheckedOutputStream cos = new CheckedOutputStream(out, new CRC32());
            ZipOutputStream zos = new ZipOutputStream(cos);
            BufferedOutputStream bos = new BufferedOutputStream(zos);
            String[] filenames = {"JDK6.chm","文本文档.txt"};
            for (String filename : filenames) {
                zos.putNextEntry(new ZipEntry(filename));
            try(InputStream in = new FileInputStream("c:/Users/apple/Desktop/" + filename)){
                    BufferedInputStream bin = new BufferedInputStream(in);
                    byte[] buffer = new byte[4096];
                    int totalBytes;
                    while((totalBytes = bin.read(buffer)) != -1){
                        bos.write(buffer, 0, totalBytes);
                    }
                    bos.flush();//清空缓冲区(强行把缓冲区中的数据写到输出流中)
                }
                catch (IOException ioe) {
                    ioe.printStackTrace();
                }
                zos.closeEntry();
            }
            zos.finish();
            System.out.println("压缩完成");
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

线程

进程 - process - 操作系统分配内存的基本单元
线程 - thread - 最小的执行单元(操作系统分配CPU资源的基本单位)
一个进程通常包含了一个或多个线程,如果没有使用多线程技术,那么进程中只有一个主线程

  • Java中创建线程有三种方式:
    1.继承Thread类,并重写run()方法
    2.实现Runnable接口并重写run()方法 - (推荐使用!!)
    由于Runnable接口是单方法接口,所以可以用lambda表达式
    3.实现Callable接口并重写call()方法 /Future接口 - 将来时(java 5+)
public class Frame extends JFrame {
    private static final long serialVersionUID = 1L;
    
    public Frame(){
        this.setTitle("窗口");
        this.setSize(400,200);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(null);
        
        JButton dButton = new JButton("Download");
        dButton.setBounds(50, 90, 100, 50);
        
        JButton aButton = new JButton("About");
        aButton.setBounds(260, 90, 100, 50);
        
        class DownloadHandler implements Runnable{
            @Override
            public void run() {                 
                    try {
                        //下载任务需要执行很长的时间,如果放在主线程中执行,那么主线程中的其他任务
                        //就会被这个耗时间的任务所阻塞,所以耗时间的任务一定要放在主线程之外的线程中执行
                        //因此下面的方法应该在一个新的线程中去调用它而不是在主线程中直接调用
                        Thread.sleep(5000);
                    } catch (InterruptedException e2) {
                        e2.printStackTrace();
                    }
                    dButton.setText("Download");
                    dButton.setEnabled(true);
            }
        }
        
        dButton.addActionListener(e -> {
            dButton.setText("loading...");
            dButton.setEnabled(false);  
            //创建并启动线程,在新的线程中执行耗时间的任务
            //启动线程是调用start()方法,不能调用run()方法
            new Thread(new DownloadHandler()).start();  
            
            //设置守护线程(不值得保留的线程 - 主线程一结束,该线程不保留)
            //thread.setDaemon(true);
        });
        
        aButton.addActionListener(e1 -> {
            JOptionPane.showMessageDialog(null, "欢迎使用!\n作者:Jack");
        });
        
        this.add(dButton);
        this.add(aButton);
    }
    
    public static void main(String[] args) {
        new Frame().setVisible(true);
    }
}
线程练习
//启动两个线程,一个输出hello,一个输出good

class printThread implements Runnable{
    private String str;
    private int counter;
        
    public printThread(String str, int counter) {
        this.str = str;
        this.counter = counter;
    }
    
    @Override
    public void run() {
        for(int i = 1; i < counter; i++){
            System.out.print(str);
        }
        
    }
    
}

class Test01 {
    
    public static void main(String[] args) {
        new Thread(new printThread("hello",100)).start();
        new Thread(new printThread("good",100)).start();
    }

    //非静态内部类的对象一定要依赖于外部类的对象才能创建
    //静态内部类的创建可以不依赖于外部类对象
}

你可能感兴趣的:(Java -- 文件压缩及线程Demo)