Java from entry to the master Chapter 15 I / O (input / output)

table of Contents

Input / output streams

File type

File input / output streams

Unbuffered input / output streams

Data input / output streams

ZIP compression input / output streams


Input / output streams

java defines a number of ways of dedicated input / output, are placed in the java.io package

Input stream: abstract class: the InputStream (input stream of bytes), Reader (character input stream)

Output streams: abstract class: the OutputStream (output stream of bytes), Writer (character output stream)

  • Read (); Reads the next byte of data from the input stream. Return int byte values ​​in the range of 0-255, not available byte return value is -1
  • read (byte [] b); length of the byte read from the input stream, and returns the number of bytes in the form of an integer
  • mark (int readlimit); placing a marker at the current position of the input stream, readlimit This parameter tells the number of bytes in the input stream prior to the failure position allows the read tag
  • RESET (); return the pointer input to the mark made to the current
  • skip (long n); n bytes to skip the input stream and returns the actual skipped bytes
  • markSupport (); if the current stream supports mark () / reset () operation returns true
  • Close (); Close this input stream associated with the stream and releases any system resources
    • All methods Not all supported InputStream InputStream classes defined, such as skip (), mark (), reset () methods only useful for certain subclasses 

File type

  • File class java.io package is the sole representative disk file object itself
  • There are three constructor
    • new File(String);
    • new File(String father, String child);
    • new File(File f, String child);

package IO;

import java.io.File;

public class FileTest {
    public static void main(String[] args) {
        //使用路径创建File对象
        //File file = new File(String pathname)
//        File file = new File("D:\\word.txt");
        File file = new File("word.txt");

        //使用父路径、子路径创建
        //File file = new File(String father, String child)
//        String fatherPath = "D:\\";
//        String childPath = "word2.txt";
//        File file2 = new File(fatherPath, childPath);

        //使用父路径对象、子路径创建
        //File file = new File(File f, String child)
//        childPath = "word3.txt";
//        File file = new File(file2.getParent(), childPath);
        if (!file.exists()) {
//            file.delete();  //删除文件
//            System.out.println("文件已删除");
        } else {
            try {
                file.createNewFile();  //创建文件
                System.out.println("文件已创建");
                String name = file.getName();  //获取文件名称
                long length = file.length();  //获取文件长度
                boolean hidden = file.isHidden(); //判断是否是隐藏文件
                System.out.println("文件名称:" + name);
                System.out.println("文件长度:" + length);
                System.out.println("是否是隐藏文件:" + hidden);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

File input / output streams

  • FileInputStream and FileOutputStream class
    • Deficiency: only these two classes provides a method of reading or byte array. As the characters occupy two bytes in the file, use a byte stream to read bad garbled, this time using a character stream can avoid this phenomenon
  • FileReader and FileWriter class
//FileInputStream与FileOutputStream类
package IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileInputStreamFileOutputStream {
    public static void main(String[] agrs) {
        File file = new File("word.txt");

        //没有文件就创建
        if (file.exists()) {
            System.out.println("存在文件" + file.getPath());
        } else {
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //写入字节流
        try {
            //创建FileOutputStream对象
            FileOutputStream outputStream = new FileOutputStream(file);
            //创建byte数组
            byte[] buy = "我有一只小毛驴,我从来也不骑。".getBytes();
            outputStream.write(buy);  //将数组中的信息写入到文件中
            outputStream.close();  //将流关闭
        } catch (Exception e) {
            e.printStackTrace();
        }

        //读出字节流
        try {
            //创建FileInputStream对象
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] byt = new byte[1024];  //创建数组
            int len = fileInputStream.read(byt);
            //将文件中的信息输出
            System.out.println("文件中的信息是:" + new String(byt, 0, len));
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Unbuffered input / output streams

flush () method is used even the contents of the buffer zone in case of compulsory written to the peripheral buffer is not full, the process is called customary refresh, flush () method is only a subclass of OutputStream class uses the cache when active, call close () method, before the system shuts down stream, will also refresh the information in the cache to disk file

  • BufferedInputStream和BufferedOutputStream类
    • Buffer can be packaged with all of InputStream class in order to achieve optimal performance of
    • Construction method
    • BufferedInputStream (InputStream in, int size); size 32-byte default
    • BufferedOutputStream (InputStream in, int size); size 32-byte default
  • BufferedReader和BufferedWriter类
    • Reader and Writer classes are inherited class
    • Common method
    • BufferedReader
      • Read (); Read a single character
      • the readLine (); to read a line of text string is returned. No data read return null
    • BufferedWriter
      • write (String s, int off, int len); written part of the string
      • flush (); cache flush stream
      • newLine (); writing a line separator
package IO;

import java.io.*;

public class students {
    public static void main(String[] agrs) {
        String[] contents = {"好久不见", "最近好吗", "常联系"};

        //写数据
        File file = new File("students.txt");  //创建File对象
        try {
            FileWriter fw = new FileWriter(file);  //创建FileWriter对象
            BufferedWriter bufw = new BufferedWriter(fw);
            for (int i = 0; i < contents.length; i++) {
                bufw.write(contents[i]);
                bufw.newLine();
            }
            bufw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //读数据
        try {
            FileReader fr = new FileReader(file);  //创建FileReader对象
            BufferedReader bufw = new BufferedReader(fr);
            String s = null;  //创建字符串对象
            int i = 0;
            //如果文件的文本行数不为null则进入循环
            while ((s = bufw.readLine()) != null) {
                i++;
                System.out.println("第" + i + "行:" + s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Data input / output streams

  • DataOutputStream DataInputStream class and classes that allow a machine-independent manner substantially the java data type read from the underlying input stream
  • Construction method
    • DataInputStream (InputStream in); Creates a DataInputStream from the specified underlying InputStream
    • DataOutputStream (OutStream out); create a new data output stream, the output stream data into the specified base
      • writeBytes (String s); Since the java unicode character encoding is two-byte, only the low-byte write bytes
      • writeChars (String s); two bytes are written
      • writeUTF (String s); written as the length in bytes of the encoded utf
package IO;

import java.io.*;

public class Example {
    public static void main(String[] args) {
        File file = new File("hi.txt");
        try {
            FileOutputStream fs = new FileOutputStream(file);
            DataOutputStream ds = new DataOutputStream(fs);
            ds.writeUTF("使用writeUTF()方法写入数据");  //使用这个写,可以读出来
            ds.writeBytes("使用writeBytes()方法写入数据");
            ds.writeChars("使用writeChars()方法写入数据");
            ds.close();  //关闭流

            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);
            System.out.println(dis.readUTF());
            dis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

ZIP compression input / output streams

java classes provide built very easy to use Class, java.util.zip package ZipOutputStream achieve compression and ZipInputStream class files / decompression

  • ZipOutputStream class, can compress the file into a .zip file
    • Constructors ZipOutputStream (OutputStream out);
  • ZipInputStream class read ZIP compressed file formats, including compressed and uncompressed entry entry
    • Constructors ZipInputStream (InputStream in);

//压缩文件
package IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

    private void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
//            if (base.length() != 0) {
//                out.putNextEntry(new ZipEntry(base + "\\")); //写入此目录的entry??
//            }
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i]);
            }
        } else {
            out.putNextEntry(new ZipEntry(base));  //创建新的进入点
            FileInputStream in = new FileInputStream(f);
            int b;
            System.out.println(base);
            while ((b = in.read()) != -1) {  //如果没有达到流的尾部
                out.write(b);                 //将自己写入当前ZIP条目
            }
            in.close();
        }
    }

    public static void main(String[] args) {
        MyZip book = new MyZip();
        try {
            book.zip("D:\\zi.zip", new File("src\\number"));
            System.out.println("done.");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
//解压缩
package IO;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

public class MyZip2 {
    public static void main(String[] args) {
        File file = new File("D:\\zi.zip");  //当前压缩文件
        try {
            ZipFile zipFile = new ZipFile(file);  //创建压缩文件对象
            ZipInputStream zin = new ZipInputStream(new FileInputStream(file)); //创建ZipInputStream对象
            ZipEntry entry = zin.getNextEntry();  //跳过根目录,获取下一个ZipEntry
            while (((entry = zin.getNextEntry()) != null)
                    && !entry.isDirectory()) {  //entry不为空,并不在同一目录下
                File tmp = new File("D:\\" + entry.getName());  //解压出的文件路径
                if (!tmp.exists()) {
                    tmp.getParentFile().mkdirs();  //创建文件父类文件夹路径
                    OutputStream os = new FileOutputStream(tmp);  //将文件目录中的文件放入输出流
                    InputStream in = zipFile.getInputStream(entry);  //用输入流读取压缩文件中制定目录中的文件
                    int count = 0;
                    while ((count = in.read()) != -1) {  //如果有输入流可以读取到数值
                        os.write(count);                 //输入流写入
                    }
                    os.close();  //关闭输出流
                    in.close();  //关闭输入流
                }
                zin.closeEntry();  //关闭当前entry
                System.out.println(entry.getName() + " unzip successfully.");
            }
            zin.close();  //关闭流

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

 

 

Published 46 original articles · won praise 0 · Views 1021

Guess you like

Origin blog.csdn.net/weixin_37680513/article/details/103492908