IO streams - other streams

Memory operation flow

This stream is not associated with any file, only the data in memory that he maintains a buffer in memory, we can go to him constantly maintain a buffer write data, we can write the data out from the buffer

ByteArrayOutputStream

ByteArrayInputStream: This class implements an output stream, wherein the data is written into a byte array. With the buffer will automatically write data growth. Using the toByteArray () and toString () obtaining data. Memory operation flow without closing

Case presentation:

public class MyTest2 {
    public static void main(String[] args) throws IOException {
      //ByteArrayOutputStream()
      //创建一个新的 byte 数组输出流。
      //创建出内存操作流 他维护着一个字节数组来充当缓冲区
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write("好好学习".getBytes());
        bos.write("天天向上".getBytes());
        bos.write("爱生活".getBytes());
        bos.write("爱Java".getBytes());
        byte[] bytes = bos.toByteArray();


      read(bytes);
}

    private static void read(byte[] bytes) throws IOException {
          /*  ByteArrayInputStream( byte[] buf)
        创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组。*/
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        byte[] bytes1 = new byte[1024];
        int len = bis.read(bytes1);
        String s = new String(bytes1, 0, len);
        System.out.println(s);

    }
}

Operating array of characters

CharArrayWrite: This class implements a character input buffer is used as a character stream.
CharArrayReader: This class implements a character buffer that can be used as a Writer. With a data buffer is written to the stream automatically increase. May be used toCharArray () and toString () obtaining data.

Case presentation:

public class MyTest3 {
    public static void main(String[] args) throws IOException {
        CharArrayWriter charArrayWriter = new CharArrayWriter();
        charArrayWriter.write("abc");
        charArrayWriter.write("abc");
        String s = charArrayWriter.toString();//调用toString()来获取字符数组
        System.out.println(s);
        char[] chars = charArrayWriter.toCharArray();//调用toCharArray()来获取字符数组
        System.out.println(chars);

    }
}

String operations

StringReader: a source string to a character stream
StringWriter: a character stream may be constructed with its output recovered string in a string buffer. Close StringWriter invalid. Methods in this class can still be called after the closing of the flow, without any exception IO

public class MyTest4 {
    public static void main(String[] args) {
        StringWriter stringWriter = new StringWriter();
        stringWriter.write("abc");
        stringWriter.write("abc");
        stringWriter.write("abc");
        stringWriter.write("abc");
        stringWriter.write("abc");
        String s = stringWriter.toString();
    }
}

ByteArrayOutputStream/ ByteArrayInputStream

ByteArrayInputStream: contains an internal buffer that contains the byte read from the stream. The internal counter tracking readthe method to provide a byte. Close ByteArrayInputStream invalid. Methods in this class can still be called after the stream has been closed, without any exception IO.

ByteArrayOutputStream: This class implements an output stream, wherein the data is written into a byte array. With the buffer will automatically write data growth. Using the toByteArray () and toString () obtaining data. Close ByteArrayOutputStream invalid. Methods in this class can still be called after the stream has been closed, without any IOException.

Case presentation: multiple mp3 files together into a mp3 file

public class MyTest {
    public static void main(String[] args) throws IOException {
        FileInputStream in1 = new FileInputStream("许巍 - 曾经的你.mp3");
        FileInputStream in2 = new FileInputStream("许巍 - 蓝莲花.mp3");
        FileOutputStream out = new FileOutputStream("C:\\Users\\jjh\\Desktop\\歌曲大连唱.mp3");
        ArrayList<FileInputStream> list = new ArrayList<>();//创建集合
        list.add(in1);
        list.add(in2);//把两手哥存入集合
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int len=0;
        byte[] bytes = new byte[1024 * 8];
        //读取两首歌的字节数据,一块先缓存到内存操作流所维护的字节数组中
        for (FileInputStream in : list) {
            while ((len = in.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            in.close();
        }
        //取出两首歌的字节数据
        byte[] allBytes = bos.toByteArray();

        //读取两首歌的字节数据,往硬盘上写
        ByteArrayInputStream bis = new ByteArrayInputStream(allBytes);
        int len2 = 0;
        byte[] bytes2 = new byte[1024 * 8];
        while ((len2=bis.read(bytes2))!=-1){
            out.write(bytes2,0,len2);
            out.flush();
        }
        out.close();
        System.out.println("合并完成");
    }
}

Print streams

He only associated with the destination, not associated source file. It can only output can not be read.

Byte stream print

PrintStream (File file): Create a new file with the specified print stream, without automatic line flushing,

PrintStream (String fileName): Creates a new print stream with the specified file name, without automatic line flushing,

Case presentation:

public class MyTest {
    public static void main(String[] args) throws IOException {
        PrintStream printStream = new PrintStream(new File("b.txt"));
        //通过创建得来的字节打印流,关联的是文件,那么你是往文件中打印数据
        printStream.write("曾梦想仗剑走天涯,看一看世界的繁华".getBytes());
        printStream.write("\r\n".getBytes());
        printStream.println("曾梦想仗剑走天涯,看一看世界的繁华");
        printStream.close();

        //System.out 获取出的这个字节打印流,关联的设备是屏幕
        PrintStream out = System.out;  //关联屏幕 out标准”输出流。此流已打开并准备接受输出数据。通常,此流对应于显示器
        out.write("abc".getBytes());
        out.print(20000);
        out.println(300000);
        System.out.println();
        out.close();

    }
}

Character print streams

PrintWriter character print streams

PrintWriter (OutputStream out, boolean autoFlush) : Creates a new PrintWriter through existing OutputStream. If auto refresh is enabled only when calling println , printf , or format only one approach might do this. Parameter 2 is whether you want to enable automatic refresh

Case Presentation 1:

public class MyTest2 {
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter printWriter = new PrintWriter("c.txt");
        printWriter.write("abc");
        printWriter.print(100);
       
        printWriter.flush();
        printWriter.close();

    }
}

Case Presentation 2:

public class MyTest3 {
    public static void main(String[] args) throws FileNotFoundException {
     // PrintWriter(OutputStream out, boolean autoFlush)
      //  通过现有的 OutputStream 创建新的 PrintWriter。

    PrintWriter printWriter = new PrintWriter(new FileOutputStream("d.txt"), true);
        //printWriter.write("abc");//因为没有调上面说的三种方法,不手动刷新的话就不显示
        printWriter.println("abc");
        printWriter.flush();
        printWriter.close();
    }
}

Case presentation 3: Copy the text file print stream

public class MyTest4 {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = new BufferedReader(new FileReader("MyTest.java"));
        PrintWriter printWriter = new PrintWriter(newFileOutputStream("MyTest222.java"),true);
        String line=null;
        while ((line=bfr.readLine())!=null){
            printWriter.println(line);//调用了println所以我们不需要手动刷新
        }
        bfr.close();
        printWriter.close();
    }
}

Random access stream

Instances of this class supports reading and writing to a random access file. Conduct random access files similar to a large byte array stored in the file system. Pointing to the presence of implicit array cursor or an index , called the file pointer ; input operation to start reading bytes from the file pointer and reading of bytes as advance the file pointer. If the random access file is created in the read / write mode, the output operation may also be used; output operation starts writing bytes from the file pointer, and as byte write and advance the file pointer. Implied array write operations after the end of the current output of the array results in extension. The file pointer by getFilePointer reading method, and by the seek setting method.

RandomAccessFile (File file, String mode) : Create a random access file from which to read and to write to (optional) stream, the file specified by the File parameter

mode parameter specifies the file to open access mode. Allowed values and their meanings are:

"r": Open as read-only. Any write result of a call object will result in an IOException.

"rw": Open for reading and writing. If the file does not exist, try to create the file.

"rws": open for reading and writing, for "rw", also require each update content or metadata files are written synchronously to the underlying storage device.

"rwd": open for reading and writing, for "rw", also require each update file content are written synchronously to the underlying storage device.

Case 1: put a song with a random access stream three copies

public class MyTest3 {
    public static void main(String[] args) throws IOException {
        RandomAccessFile in = new RandomAccessFile("许巍 - 曾经的你.mp3", "rw");
        RandomAccessFile out = null;
        byte[] bytes = new byte[1024];
        int len = 0;
        for (int i = 0; i < 3; i++) {
            out = new RandomAccessFile((i + 10) + "许巍 - 曾经的你.mp3", "rw");
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            in.seek(0);//把文件指针置于文件的开头
            out.close();
        }
        in.close();
    }
}

Case 2: Copy songs breakpoint

public class MyTest4 {
    public static void main(String[] args) throws IOException {
        RandomAccessFile in = new RandomAccessFile("许巍 - 蓝莲花.mp3", "rw");
        File mbFile = new File("C:\\Users\jjh\\Desktop\\许巍 - 蓝莲花22222.mp3");
        RandomAccessFile out = new RandomAccessFile(mbFile, "rw");

        //第二次来复制了
        String s = new BufferedReader(new FileReader("ls.txt")).readLine();
       //读取临时文件
        long len2 = Long.parseLong(s);//获取临时文件的长度(向下转型)
        if(mbFile.exists()&&mbFile.length()==len2){
        //如果临时文件存在而且目标文件的长度和临时文件相等的话继续执行
            in.seek(len2);//把指针位置置于len2这样就可以断点下载
            out.seek(len2);
        }else{
            in.seek(0);//设置文件指针的位置
            out.seek(0);
        }


        int len=0;
        byte[] bytes = new byte[1024];
        int i=1;
        try {
            while ((len = in.read(bytes)) != -1) {
                //i++;
                out.write(bytes, 0, len);
              /*  if(i>=2500){
                    System.out.println(1/0);
                }*/   //这是自己制造的异常情况让复制终止

            }
        }catch (Exception e){
            long filePointer = in.getFilePointer(); //获取文件指针的位置
            System.out.println(filePointer);
            PrintWriter printWriter = new PrintWriter(new File("ls.txt"));
            //创建一个临时文件来记录文件复制的字节数
            printWriter.println(filePointer);
            printWriter.flush();
            printWriter.close();
        }

        in.close();
        out.close();
    }
}

Other serial input stream (stream order)

SequenceInputStream: represents the logical series of other input streams. It, and read from the input stream is an ordered collection started from the first input stream, until the end of the file, then reads the input stream from the second, and so on, until the end of the last contains a file input stream until

SequenceInputStream (InputStream s1, InputStream s2) : by remembering these two parameters to initialize the newly created SequenceInputStream (these two parameters will be sequentially read, the first read s1, and then reads the S2), to provide read from SequenceInputStream byte

Case presentation: The order of the stream three songs makes up a song

public class MyTest {
    public static void main(String[] args) throws IOException {
        FileInputStream in1 = new FileInputStream("许巍 - 曾经的你.mp3");
        FileInputStream in2 = new FileInputStream("许巍 - 蓝莲花.mp3");
        FileInputStream in3 = new FileInputStream("许巍 - 蓝莲花.mp3");
        FileOutputStream out = new FileOutputStream("gequ.mp3");//输出
        
        SequenceInputStream sequenceInputStream = new SequenceInputStream(in1, in2);
        SequenceInputStream sequenceInputStream1 = new SequenceInputStream(sequenceInputStream, in3);
        int len=0;
        byte[] bytes = new byte[1024 * 8];
        while ((len=sequenceInputStream1.read(bytes))!=-1){
            out.write(bytes,0,len);
            out.flush();
        }
        out.close();
        sequenceInputStream1.close();
    }
}

Properties

Properties Inheritance Hashtable is a set of double row, a predetermined key is a string type

Case Presentation 1:

public class MyTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("username", "张三");
        properties.setProperty("password", "123456");
        String username = properties.getProperty("username");
        //当这个键对应的值得没找到,可以返回这个备用值,参数2 可以指定一个备用的值
        String pwd = properties.getProperty("password","654321");
        System.out.println(username);
        System.out.println(pwd);
    }
}

Case Presentation 2: The collection of key attributes of the data stored in the configuration file write (store ())

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.setProperty("username", "张三");
        properties.setProperty("password", "123456");
        //参数2:是注释 一般给个null 写个默认注释
        properties.store(new FileOutputStream("user.properties"),"hehehe");
        
        

Case presentation 3: The profile of key data, the properties will be set again

public class MyTest3 {
    public static void main(String[] args) throws IOException {
        //Properties 读取配置文件,对文件有要求,1.键值对,是 = 拼接 2.属性集合读取到的这个文件的后缀名是以.properties
        Properties properties = new Properties();
        //读取配置文件
        properties.load(new FileInputStream("user.properties"));
        System.out.println(properties);

    }
}

Case presentation 4:

public class MyTest04 {
/*我有一个文本文件file.txt,我知道数据是键值对形式的,但是不知道内容是什么。
  请写一个程序判断是否有"lisi"这样的键存在,如果有就改变其实为"100"
  file.txt文件内容如下:
zhangsan = 90
lisi = 80
wangwu = 85*/
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("file.txt"));
        //先读写这个文件
        Set<String> names = properties.stringPropertyNames();
         //stringPropertyNames()
        //返回此属性列表中的键集,其中该键及其对应值是字符串,如果在主属性列表中未找到同名的键,则还包括默认属性列表中不同的键。其键或值不是 String 类型的属性被忽略
        if (names.contains("lisi")){
          properties.setProperty("lisi","100");
          properties.store(new FileOutputStream("d.txt"),null);
            //最后写入保存
            System.out.println(properties);
        }

Guess you like

Origin www.cnblogs.com/godles/p/11892729.html