Java----其他流

Java----其他流

1.数据流

能够读写基本数据类型和字符串
输入流:DataInputStream
输出流:DataOutputStream

2.内存操作流

这个流不关联任何文件,只能在内存入数据.
内存操作流,自己在内存中维护着一个缓冲区,我们可以往他维护的缓冲区不断的
写入数据,也可以从缓冲区中取出我们写入的数据
ByteArrayOutputStream
 ByteArrayInputStream

3.打印流

只关联目的地,不关联源文件,也就是说它只能输出,不能读取。
字节打印流---PrintStream
字符打印流---PrintWriter
PrintStream(File file)
        创建具有指定文件且不带自动行刷新的新打印流
PrintStream(String fileName)
        创建具有指定文件名称且不带自动行刷新的新打印流

4.Scanner:扫描器

Scanner(InputStream source)
        构造一个新的 Scanner,它生成的值是从指定的输入流扫描的。
Scanner(File source)
        构造一个新的 Scanner,它生成的值是从指定文件扫描的。
使用Scanner和字符打印流配合复制文本文件 
代码演示:
public class MyTest6 {
    public static void main(String[] args) throws FileNotFoundException {
        //使用Scanner和字符打印流配合复制文本文件
        Scanner scanner = new Scanner(new File("MyTest.java"));
        PrintWriter printWriter = new PrintWriter(new FileOutputStream("a.java"), true);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            printWriter.println(s);
        }

        scanner.close();
        printWriter.close();

    }
}

5.随机访问流

RandomAccessFile
        此类的实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储
        在文件系统中的一个大型 byte 数组。存在指向该隐含数组的光标或索引,
        称为文件指针;
        指针开始读取字节,并随着对字节的读取而前移此文件指针。
RandomAccessFile(File file, String mode)
        创建从中读取和向其中写入(可选)的随机访问文件流,
        该文件由 File 参数指定。

6.序列化与反序列化

序列化:将一个Java对象,保存到文件中
反序列化:将文件中Java对象,再都会内存

7.压缩流与解压缩流

代码演示:
public class MyTest {
    public static void main(String[] args) throws IOException {
        //压缩流与解压缩流src
       // ZipOutputStream 压缩流
       // ZipInputStream 解压流
        //压缩单个文件
        //创建压缩流,关联压缩文件
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("C:\\Users\\ShenMouMou\\Desktop\\hehe.zip"));
        //封装待压缩的文件
        File srcFile = new File("C:\\Users\\ShenMouMou\\Desktop\\歌曲大连唱.mp3");
        //创建一个高效的字节流,封装一下压缩流

        BufferedOutputStream bos = new BufferedOutputStream(zipOut);
        //ZipEntry 表示压缩条目 把你要压缩的文件封装成压缩条目
        ZipEntry zipEntry = new ZipEntry(srcFile.getName());
        //再把压缩条目放到 压缩流中
        zipOut.putNextEntry(zipEntry);

        //创建输入流,读取源文件进行压缩
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));

        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=bis.read(bytes))!=-1){
            bos.write(bytes,0,len);
        }
        bos.close();
        zipOut.close();
        bis.close();
        System.out.println("压缩完成");
    }
}

发布了25 篇原创文章 · 获赞 3 · 访问量 318

猜你喜欢

转载自blog.csdn.net/weixin_45686974/article/details/103174741
今日推荐