java 流

2020-04-21  本文已影响0人  relax_小罗罗

java 流

流是一组有序的数据序列,根据操作的类型,可分为输入流输出流两种。I/O(input/output)流提供了一条通道程序,可以使用这条通道把源中的字节序列送到目的地。虽然I/0流通常与磁盘文件存取有关,但是程序的源和目的地也可以是键盘,鼠标,内存或者显示器的窗口。
所有输入流类都是抽象类InputStream(字节输入流) 或是抽象了Reader(字符输入流)的子类:而所有输出流都是抽象类OutputStream(字节输出流) 或抽象类Writer(字符输出流)的子类;

inputStream

该类所有方法遇到错误都会引发IOException异常。

read() 从输入流中读取数据的下一个字节。返回0-255范围内的int字节值。流末尾返回-1;
read(byte[] b) 从输入流中读入一定长度的字节,并以整数的形式返回字节数;
mark(int redlimit) 在输入流的当前位置放一个标记,redlimit参数告诉此输入流在标记位置是小钱允许读取的字节数;
reset() 将输入指针返回当前所做的标记处;
skip(long n) 跳过N个字节并返回实际跳过的字节数;
markSupported() 如果当前输入流支持 mark/reset 操作,就返回true;
close() 关闭此输入流并释放与该流关联的所有系统资源。

层次图

并不是所有的InputStream类的子类都支持InputStream中定义的方法,如skip(),mark(),reset()等方法只对某些子类有用
java中的字符是Unicode编码,是双字节的,InputStream 是用来处理字节的,并不太适合字符文本。Java提供了一套单独的Reader来处理文本。

33.png

outputStream

write(int b) 将指定的字节写入此输出流;
write(byte[] b) 将b个字节从指定的byte数组写入此输出流;
write(byte[]b,int off,int len) 将指定byte数组中从偏移量off开始的len个字节写入此输出流;
flush() 彻底完成输出并清空缓存区;
close() 关闭输出流;


111

Writer类的用法跟outputStream用法基本一致;


55.png

File文件的创建于删除

       //创建
        File file=new File("d:/test/1.txt");
        //根据路径创建
        File file1=new File("d:/test","2.txt");
        File fileBasePath = new File("d:/test");
        File file3=new File(fileBasePath,"3.txt");
        File testFile = new File("I:\\test\\1.txt");
        if (testFile.exists()) {
            testFile.delete();
            System.out.println("文件已删除");
        } else {
            try {
                testFile.createNewFile();
                System.out.println("文件已创建");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

getName() String 获取文件的名称;
canRead() boolean 判断文件是否为可读的;
canWrite() boolean 判断文件是否为可写的;
exits() boolean 判断文件是否存在;
length() long 获取文件长度,以字节为单位;
getAbsolutePath() String 获取文件的绝对路径;
getParent() String 获取文件的父路径;
isFile() boolean 判断是否是一个文件;
isDirectory boolean 判断是否是一个目录;
isHidden() boolean 判断文件是否为隐藏文件;
lastModified() long 获取文件最后修改时间;

  File testFile = new File("I:\\test\\1.txt");
        if (testFile.exists()) {
            System.out.println("文件的名称为:"+testFile.getName());
            System.out.println("文件的长度为:"+testFile.length());
            System.out.println("该文件是隐藏文件吗?:"+testFile.isHidden());
            System.out.println("文件的最后修改时间为::"+testFile.lastModified());
            testFile.getName();
            testFile.delete();
            System.out.println("文件已删除");
        } else {
            try {
                testFile.createNewFile();
                System.out.println("文件已创建");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

FileInputStream和FileOutputStream

FileInputStream
常用构造方法:
FileInputStream(String name);
FileInputStream(File file);
可以为空,但是不能是一个被其他程序打开的文件
FileOutputStream(String name);
FileOutputStream(File file);

 public static void main(String[] args) {
        try {
            FileOutputStream out =new FileOutputStream("I:\\test\\1.txt");
            byte[] b="床前明月光,啦啦啦".getBytes();
            out.write(b);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileInputStream in=new FileInputStream("I:\\test\\1.txt");
            byte[] b=new byte[1024];
            int len=in.read(b);
            System.out.println("文件中的信息是:"+new String(b,0,len));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

FileReader和FileWriter类

由于汉子占用两个字节流,使用inputStream 读取不好的容易造成乱码,故使用Reder和Wirter类;

public class Ftest extends JFrame { // 创建类,继承Jframe类
    private JScrollPane scrollPane;
    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null; // 创建面板对象
    private JTextArea jTextArea = null; // 创建文本域对象
    private JPanel controlPanel = null; // 创建面板对象
    private JButton openButton = null; // 创建按钮对象
    private JButton closeButton = null; // 创建按钮对象

    private JTextArea getJTextArea() {
        if (jTextArea == null) {
            jTextArea = new JTextArea();
        }
        return jTextArea;
    }

    private JPanel getControlPanel() {
        if (controlPanel == null) {
            FlowLayout flowLayout = new FlowLayout();
            flowLayout.setVgap(1);
            controlPanel = new JPanel();
            controlPanel.setLayout(flowLayout);
            controlPanel.add(getOpenButton(), null);
            controlPanel.add(getCloseButton(), null);
        }
        return controlPanel;
    }

    private JButton getOpenButton() {
        if (openButton == null) {
            openButton = new JButton();
            openButton.setText("写入文件"); // 修改按钮的提示信息
            openButton
                    .addActionListener(new java.awt.event.ActionListener() {
                        // 按钮的单击事件
                        public void actionPerformed(ActionEvent e) {
                            // 创建文件对象
                            File file = new File("I:\\test\\1.txt");
                            try {
                                // 创建FileWriter对象
                                FileWriter out = new FileWriter(file);
                                // 获取文本域中文本
                                String s = jTextArea.getText();
                                out.write(s); // 将信息写入磁盘文件
                                out.close(); // 将流关闭
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    });
        }
        return openButton;
    }

    private JButton getCloseButton() {
        if (closeButton == null) {
            closeButton = new JButton();
            closeButton.setText("读取文件"); // 修改按钮的提示信息
            closeButton
                    .addActionListener(new java.awt.event.ActionListener() {
                        // 按钮的单击事件
                        public void actionPerformed(ActionEvent e) {
                            File file = new File("I:\\test\\1.txt"); // 创建文件对象
                            try {
                                // 创建FileReader对象
                                FileReader in = new FileReader(file);
                                char byt[] = new char[1024]; // 创建char型数组
                                int len = in.read(byt); // 将字节读入数组
                                // 设置文本域的显示信息
                                jTextArea.setText(new String(byt, 0, len));
                                in.close(); // 关闭流
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    });
        }
        return closeButton;
    }

    public Ftest() {
        super();
        initialize();
    }

    private void initialize() {
        this.setSize(300, 200);
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
    }

    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getScrollPane(), BorderLayout.CENTER);
            jContentPane.add(getControlPanel(), BorderLayout.SOUTH);
        }
        return jContentPane;
    }

    public static void main(String[] args) { // 主方法
        Ftest thisClass = new Ftest(); // 创建本类对象
        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        thisClass.setVisible(true); // 设置该窗体为显示状态
    }
    /**
     * @return
     */
    protected JScrollPane getScrollPane() {
        if (scrollPane == null) {
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(getJTextArea());
        }
        return scrollPane;
    }
}

BufferedInputStream和BufferedOutputStream

缓存是I/O的一种优化,缓存为流增加了内存缓存区,有了缓存区,是的在流上执行skip(),mark(),reset都成为可能
构造方法
BufferedInputStream(InputStream in);
BufferedInputStream(InputStream in,int size);

BufferedInputStream(OutputStream out);
BufferedInputStream(OutputStream out ,int size);

**flush()方法只对使用缓存区的OutputStream类的子类有效,当调用close()方法时,系统在关闭流之前,也会将魂村区中的信息保存到磁盘文件中。

BufferedReader和BufferedWriter

BufferedReader常用方法:
read() 读取单个字符;
redLine() 读取一个文本行,并将其返回为字符串。若无数据可读,贼返回NULL

BufferedWriter常用方法
write(String s,int off,int len) 写入字符串的一部分
flush 刷新该流的缓存;
newLine(): 写入一个分隔符;

public static void main(String args[]) { // 主方法
        // 定义字符串数组
        String content[] = { "好久不见", "最近好吗", "常联系" };
        File file = new File("I:\\test\\1.txt"); // 创建文件对象
        try {
            FileWriter fw = new FileWriter(file); // 创建FileWriter类对象
            // 创建BufferedWriter类对象
            BufferedWriter bufw = new BufferedWriter(fw);
            for (int k = 0; k < content.length; k++) { // 循环遍历数组
                bufw.write(content[k]); // 将字符串数组中元素写入到磁盘文件中
                bufw.newLine(); // 将数组中的单个元素以单行的形式写入文件
            }
            bufw.close(); // 将BufferedWriter流关闭
            fw.close(); // 将FileWriter流关闭
        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        }
        try {
            FileReader fr = new FileReader(file); // 创建FileReader类对象
            // 创建BufferedReader类对象
            BufferedReader bufr = new BufferedReader(fr);
            String s = null; // 创建字符串对象
            int i = 0; // 声明int型变量
            // 如果文件的文本行数不为null,则进入循环
            while ((s = bufr.readLine()) != null) {
                i++; // 将变量做自增运算
                System.out.println("第" + i + "行:" + s); // 输出文件数据
            }
            bufr.close(); // 将FileReader流关闭
            fr.close(); // 将FileReader流关闭
        } catch (Exception e) { // 处理异常
            e.printStackTrace();
        }
    }

zip的压缩与解压

ZipOutputStream常用方法
putNextEntry(ZipEntry e) 开始写一个新的ZipEntry,并将流内的位置移至此entry所指数据的开头
write(byte[] b,int off,int len) 将字节数组写入到当前ZIP条目数据;
finish 写入zip输出流内容,无数关闭OutputStream;
setComment(String comment) 可设置此ZIP文件的注释文字;

  private void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                zipFileName)); // 创建ZipOutputStream类对象
        zip(out, inputFile, ""); // 调用方法
        System.out.println("压缩中…"); // 输出信息
        out.close(); // 将流关闭
    }

    private void zip(ZipOutputStream out, File f, String base)
            throws Exception { // 方法重载
        if (f.isDirectory()) { // 测试此抽象路径名表示的文件是否是一个目录
            File[] fl = f.listFiles(); // 获取路径数组
            if (fl.length == 0) {//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
                System.out.println(base + File.separator);
                out.putNextEntry(new ZipEntry(base + File.separator));
            }else {
                for (int i = 0; i < fl.length; i++) { // 循环遍历数组中文件
                    zip(out, fl[i], base +File.separator+ fl[i].getName());
                }
            }

        } else {
            out.putNextEntry(new ZipEntry(base)); // 创建新的进入点
            // 创建FileInputStream对象
            FileInputStream in = new FileInputStream(f);
            System.out.println(base);
            BufferedInputStream bis = new BufferedInputStream(in);
            int len;
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf, 0, 1024)) != -1) {
                out.write(buf, 0, len);
            }
            bis.close();
            in.close(); // 关闭流
        }
    }

    public static void main(String[] temp) { // 主方法
        zipDemo book = new zipDemo(); // 创建本例对象
        try {
            // 调用方法,参数为压缩后文件与要压缩文件
            book.zip("test.zip", new File("I:\\test"));
            System.out.println("压缩完成"); // 输出信息
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

ZipInputStream的常用方法
read(byte[] b,int off,int len) 读取目标b数组内off偏移量的位置,长度是len字节;
availabe() 判断是否已读完目前entry所制定的数据。已读完返回0,否则返回1;
closeEntry() 关闭当前zip条目并定位流以读取下一条;
skip(long n) 跳过当前zip条目中指定的字符数;
getNextEntry 读取下一个zipEntry,并将流内的位置移至该entry所指数据的开头;
createZipEntry(String name) 以指定的name参数创建一个zipEntry对象;

    public static void main(String[] temp) {
        ZipInputStream zin; // 创建ZipInputStream对象
        try { // try语句捕获可能发生的异常
            zin = new ZipInputStream(new FileInputStream("I:\\test.zip"));
            ZipFile zipFile=new ZipFile("test.zip");
            // 实例化对象,指明要进行解压的文件
            ZipEntry entry = null; // 获取下一个ZipEntry
            File fileBase=new File("d:\\" + File.separator+"test");
            if (!fileBase.exists()) { // 如果该文件不存在
                fileBase.mkdirs();// 创建文件所在文件夹
            }
            while (((entry = zin.getNextEntry()) != null)
                    && !entry.isDirectory()) {
                // 如果entry不为空,并不在同一目录下
                File file = new File("d:\\" + File.separator+"test"+File.separator+entry.getName()); // 获取文件目录
                System.out.println(file);
                if(!file.exists()){
                    file.getParentFile().mkdirs();
                    OutputStream out =new FileOutputStream(file);
                    InputStream in=zipFile.getInputStream(entry);
                    int len=0;
                    byte[] buf = new byte[1024];
                    while ((len=in.read(buf, 0, 1024))!=-1){
                        out.write(buf, 0, len);
                    }
                }

                zin.closeEntry(); // 关闭当前entry
                System.out.println(entry.getName() + "解压成功");
            }
            zin.close(); // 关闭流
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
上一篇下一篇

猜你喜欢

热点阅读