import java.io.*;

public class Test {
    public static void main(String[] args) {
//        BufferedInputFile.test();
//        MemoryInput.test();
//        FormattedMemoryInput.test();
//        TestEOF.test1();
//        TestEOF.test2();
//        BasicFileOutput.test();
//        FileOutputShotcut.test();
//        StoringAndRecoveringData.test();
        UsingRandomAccessFile.test();
    }

}

/*
    打开一个文件用于字符输入,为提高速度,需要用到缓冲
 */
class BufferedInputFile {
    public static String read(String file) {
        String result = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str=reader.readLine()) != null) {
                sb.append(str+"\n");
            }
            reader.close();
            result=sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void test() {
        System.out.println(read("./src/Test.java"));
    }
}

/*
    BufferedInputFile.read()读入的String结果被用来创造一个StringReader
    然后调用read()每次读取一个字符,并将它送到控制台
 */
class MemoryInput {
    public static void test() {
        StringReader sr = new StringReader(BufferedInputFile.read("./src/Test.java"));
        int c;
        try {
            while ((c = sr.read()) != -1) {
                System.out.println((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/*
    要读取格式化数据,可以使用DataInputStream,它是一个面向字节的I/O类(不是面向
    字符的)。因此我们必须使用InputStream类而不是Reader类
 */
class FormattedMemoryInput {
    public static void test() {
        try{
            DataInputStream in = new DataInputStream(
                    new ByteArrayInputStream(
                            BufferedInputFile.read("./src/Test.java").getBytes()
                    )
            );

            while (true) {
                System.out.println((char)in.readByte());
            }
        } catch (IOException e) {
            System.out.println("End of stream");
            e.printStackTrace();
        }
    }
}

/*
    利用avaliable()来查看还有多少可供读取的字符,用于检测输入是否结束
 */
class TestEOF {
    //需要为ByteArrayInputStream提供字节数组作为构造参数
    public static void test1() {
        try{
            DataInputStream in = new DataInputStream(
                    new ByteArrayInputStream(
                            BufferedInputFile.read("./src/Test.java").getBytes()
                    )
            );

            while (in.available()!=0) {
                System.out.println((char)in.readByte());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //这儿DataInputStream和BufferedInputStream都是装饰器
    public static void test2() {
        try {

            DataInputStream in = new DataInputStream(
                    new BufferedInputStream(
                            new FileInputStream("./src/Test.java")
                    )
            );
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

/*
    为了提供格式化机制,FileWriter被装饰成了PrintWriter
 */
class BasicFileOutput {
    private static String file = "./src/file3";

    public static void test() {

        try {
            //创建文件输入流
            BufferedReader in = new BufferedReader(
                    new StringReader(
                            BufferedInputFile.read("./src/Test.java")));

            //创建文件输出流
            PrintWriter out = new PrintWriter(
                    new BufferedWriter(
                            new FileWriter(file)));

            //从输入流写到输出流
            int lineCount=1;
            String str;
            while ((str = in.readLine()) != null) {
                out.println(lineCount++ + " : "+str);
            }
            out.close();
            System.out.println(BufferedInputFile.read(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

/*
    PrintWriter的辅助构造器,可以减少装饰工作
 */
class FileOutputShotcut {
    private static String file = "./src/file4";

    public static void test() {

        try {
            //创建文件输入流
            BufferedReader in = new BufferedReader(
                    new StringReader(
                            BufferedInputFile.read("./src/Test.java")));

            //创建文件输出流
            PrintWriter out = new PrintWriter(file);

            //从输入流写到输出流
            int lineCount=1;
            String str;
            while ((str = in.readLine()) != null) {
                out.println(lineCount++ + " : "+str);
            }
            out.close();
            System.out.println(BufferedInputFile.read(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/*
    DataOutputStream输出可供另一个流恢复的数据
 */
class StoringAndRecoveringData {
    public static void test() {

        try{
            //建立输出流,输出数据
            DataOutputStream out = new DataOutputStream(
                    new BufferedOutputStream(
                            new FileOutputStream("./src/file4")));

            //建立输入流,恢复数据
            DataInputStream in = new DataInputStream(
                    new BufferedInputStream(
                            new FileInputStream("./src/file4")));

            out.writeDouble(3.1415926);
            out.writeUTF("That was pi");
            out.writeDouble(1.41413);
            out.writeUTF("Square root of 2");
            out.close();

            System.out.println(in.readDouble());
            System.out.println(in.readUTF());
            System.out.println(in.readDouble());
            System.out.println(in.readUTF());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

/*
    RandomAcccessFile拥有读取基本烈性和UTF-8字符串的各种具体的方法,同时seek()
    方法可以在文件中到处移动
 */
class UsingRandomAccessFile {
    private static String file = "./src/file5";

    private static void display(){
        try{
            RandomAccessFile rf = new RandomAccessFile(file,"r");
            for (int i = 0; i < 7; i++) {
                System.out.println("VALUE "+i+": "+rf.readDouble());
            }
            System.out.println(rf.readUTF());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void write() {
        try{
            RandomAccessFile rf = new RandomAccessFile(file,"rw");
            for (int i = 0; i < 7; i++) {
                rf.writeDouble(i*1.414);
            }
            rf.writeUTF("The end of the file");
            rf.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void test() {
        write();
        display();

        try{
            RandomAccessFile rf = new RandomAccessFile(file,"rw");
            rf.seek(5*8);

            rf.writeDouble(47.01);
            rf.close();

            display();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Java编程思想:I/O的典型使用方式的更多相关文章

  1. 24.JAVA编程思想——违例差错控制

    24.JAVA编程思想--违例差错控制 Java 的基本原理就是"形式错误的代码不会执行". 与C++类似,捕获错误最理想的是在编译期间,最好在试图执行程序曾经.然而.并不是全部错 ...

  2. Java编程思想 第21章 并发

    这是在2013年的笔记整理.现在重新拿出来,放在网上,重新总结下. 两种基本的线程实现方式 以及中断 package thread; /** * * @author zjf * @create_tim ...

  3. JAVA编程思想——分析阅读

    需要源码.JDK1.6 .编码风格参考阿里java规约 7/12开始 有点意识到自己喜欢理论大而泛的模糊知识的学习,而不喜欢实践和细节的打磨,是因为粗心浮躁导致的么? cron表达式使用 设计能力.领 ...

  4. 《Java编程思想》读书笔记(二)

    三年之前就买了<Java编程思想>这本书,但是到现在为止都还没有好好看过这本书,这次希望能够坚持通读完整本书并整理好自己的读书笔记,上一篇文章是记录的第一章到第十章的内容,这一次记录的是第 ...

  5. 《Java编程思想》读书笔记(三)

    前言:三年之前就买了<Java编程思想>这本书,但是到现在为止都还没有好好看过这本书,这次希望能够坚持通读完整本书并整理好自己的读书笔记,上一篇文章是记录的第十一章到第十六章的内容,这一次 ...

  6. 《Java编程思想》读书笔记(五)

    前言:本文是<Java编程思想>读书笔记系列的最后一章,本章的内容很多,需要细读慢慢去理解,文中的示例最好在自己电脑上多运行几次,相关示例完整代码放在码云上了,码云地址:https://g ...

  7. JAVA编程思想(第四版)学习笔记----4.8 switch(知识点已更新)

    switch语句和if-else语句不同,switch语句可以有多个可能的执行路径.在第四版java编程思想介绍switch语句的语法格式时写到: switch (integral-selector) ...

  8. 《Java编程思想》学习笔记(二)——类加载及执行顺序

    <Java编程思想>学习笔记(二)--类加载及执行顺序 (这是很久之前写的,保存在印象笔记上,今天写在博客上.) 今天看Java编程思想,看到这样一道代码 //: OrderOfIniti ...

  9. #Java编程思想笔记(一)——static

    Java编程思想笔记(一)--static 看<Java编程思想>已经有一段时间了,一直以来都把笔记做在印象笔记上,今天开始写博客来记录. 第一篇笔记来写static关键字. static ...

  10. [Java编程思想-学习笔记]第3章 操作符

    3.1  更简单的打印语句 学习编程语言的通许遇到的第一个程序无非打印"Hello, world"了,然而在Java中要写成 System.out.println("He ...

随机推荐

  1. QT在release版本产生pdb文件

    ##环境说明 QtCreator QtLibrary 编译器 Qt Creator 2.7.0 4.8.4-msvc msvc9.0(VS2008) ##背景说明 >项目中需要对发布版本追踪崩溃 ...

  2. Android零基础入门第48节:可折叠列表ExpandableListView

    原文:Android零基础入门第48节:可折叠列表ExpandableListView 上一期学习了AutoCompleteTextView和MultiAutoCompleteTextView,你已经 ...

  3. Docker镜像与容器命令 专题

    https://yeasy.gitbooks.io/docker_practice/content/install/mirror.html docker的工作流程图: 至少需要配备三样东西去使用doc ...

  4. visual studio 2017 添加MSDN

    原文:visual studio 2017 添加MSDN 1.启动VS2017的安装软件,点击更改,进行MSDN帮助组件添加安装. 2.在单个组件中找到"Help Viewer", ...

  5. 在asp.net 中web.config配置错误页

    每当用户访问错误页面时,会出现不友好的错误页面,所以为了防止这种不友好,我们在web.config中的<system.web>节点下配置 <customErrors>,在出现比 ...

  6. ObjectForScripting 注册

                c#和javascript函数的相互调用(ObjectForScripting 的类必须对 COM 可见.请确认该对象是公共的,或考虑向您的类添加 ComVisible 属性. ...

  7. AnmpServer 0.9.3 发布

    摘要: AnmpServer是一款集成Apache服务器.Nginx服务器.MySQL数据库.PHP解释器的整合软件包.免去了开发人员将时间花费在繁琐的配置环境过程,从而腾出更多精力去做开发,助力PH ...

  8. ElasticSearch学习(一):ElasticSearch介绍

    一.ElasticSearch是什么? ElasticSearch是一款非常强大的.基于Lucene的开源搜索及分析引擎,可以帮助你从海量数据中,快速找到相关的数据信息. 比如,当你在GitHub上搜 ...

  9. Arm架构下VUE环境的安装

    最近因为项目需要在arm环境下搭建vue环境,网上有基于Linux的 教程,路径略有不同,现整理如下 1.安装文件下载 1.下载地址:http://nodejs.cn/download/ 2.选择一个 ...

  10. valet环境PHPstorm+xdebug调试

    1.安装xdebug 2.配置xdebug zend_extension="/usr/local/Cellar/php@7.2/7.2.18/pecl/20170718/xdebug.so& ...