美文网首页java学习
Java I/O (二)--I/O流的使用

Java I/O (二)--I/O流的使用

作者: LilacZiyun | 来源:发表于2016-09-03 18:00 被阅读77次

    输入

    从缓存输入

    一般进行文件的输入输出时,都会采用缓存的方式,这样能够提高应用程序性能。如果想要打开一个文件进行字符输入的话,可以使用Java I/O 类库的BufferedReader类,下例展示了该类的简单使用。

    public class BufferedInputFile {
        
        public static void main(String[] args)throws IOException {
            String filename = "fruit";
            String content = read(filename);
            print(content);
        }
    
        static String read(String filename) throws IOException {
            BufferedReader in = new BufferedReader(new FileReader(filename));
            StringBuilder sb = new StringBuilder();
            String line = in.readLine();
            while (line != null) {
                sb.append(line);
                sb.append("\n");    // 注意添加换行符,因为readLine()方法会将换行符剔除
                line = in.readLine();
            }
            in.close();
            return sb.toString();
        }
    }
    
    

    从内存输入

    当需要直接从内存输入数据时,可以使用StringReader或DataInputStream,其中DataInputStream可以读取格式化数据,下面通过一个小实例演示DataInputStream的使用。

    public class DataInputStreamTest {
        
        public static void main(String[] args)throws IOException {
            String str = "A string using for DataInputStream test!";
            DataInputStream dis = new DataInputStream(new ByteArrayInputStream(str.getBytes()));
            while (dis.available() != 0){
                printnb((char)dis.readByte());
            }
            print();
            dis.close();
        }
    }
    
    // Output:
    A string using for DataInputStream test!
    

    注:

    • DataInputStream类的readByte()方法每次均返回一个int类型的字节,所以需要通过类型转换才能获得我们想要的char类型;
    • readByte()方法一次一个字节地读取数据,这种情况下,任何字节均是有效字节,所以不能通过该方法的返回值来判断输入是否结束,不过可以如上例所示,通过使用available()方法来达到目的。available()方法会返回一个int,表示输入中还有多少可供读取的字符。不过available()方法也需要谨慎使用,因为该方法会随所读取的媒介类型的不同而发生变化。

    输出

    当需要向流中输出数据时,可以使用PrintWriter类。
    PrintWriter因其简单易用、灵活而强大的格式化输出能力从而在字符流输出方面得到了越来越多的使用。PrintWriter提供了8个构造函数,分别用于不同参数条件下的对象创建。

    // 通过指定文件/文件名创建一个PrintWriter
    PrintWriter(File file)
    PrintWriter(File file, String csn)
    PrintWriter(String fileName)
    PrintWriter(String fileName, String csn)
    
    //通过指定一个输出流创建一个PrintWriter
    PrintWriter(OutputStream out)
    PrintWriter(OutputStream out, boolean autoFlush)
    
    //通过指定一个Writer对象创建一个PrintWriter
    PrintWriter(Writer out)
    PrintWriter(Writer out, boolean autoFlush)
    

    PrintWriter的简单使用

    public class PrintWriterTest {
    
        public static void main(String[] args) throws IOException{
            // 通过PrintWriter向名为“char”的文件输入数据
            PrintWriter out = new PrintWriter("char");
            String name = "Hellen";
            int age = 8;
            float weitht = 25.34f;
            char sex = '女';
    
            out.write("A string in class PrintWriterTest!");
            out.println();
            out.printf("name: %s;  age: %d; sex: %c; weight: %5.2f;", name, age, sex, weitht);
            out.println();
            out.close();
        }
    }
    
    // 文件内容:
    A string in class PrintWriterTest!
    name: Hellen;  age: 8; sex: 女; weight: 25.34;
    

    注:

    • 当使用前6个构造器创建PrintWriter对象时,会先在内部创建一个BufferedWriter,然后再使用该BufferedWriter作为参数去调用最后一个构造器以完成PrintWriter对象的创建,因此通过前6个构造器创建的PrintWriter本身是带有BufferedWriter缓冲的,而通过后两个构造器创建的PrintWriter对象是否具有缓冲能力则取决于所提供的Writer参数本身是否带有缓冲,类实现并不自动为其提供。
    • 为了使用的简单性,除了构造器外,PrintWriter类的其他方法并不抛出 I/O 异常,要得知 IO操作过程是否出错,可通过调用checkError()方法进行查询,不过该方法会同时清空缓冲区。
    • PrintWriter内部提供write()方法和print()方法进行写入操作,具体实现为:print()方法内部会先将待写入数据转为String类型,然后调用write()方法(同步)完成写入操作。

    实用工具类

    在进行常规的项目开发时,通常会遇到比较多的IO操作,但装饰器模式的使用,使得Java IO 操作相对比较复杂,而且如果在每个需要进行 IO 操作的地方都直接使用Java类库的话,会使得写出的代码比较臃肿,不利于阅读。由此可见,自己提供一个 IO 操作的工具类就显得非常有意义了。

    public class FileUtils extends ArrayList<String> {
    
        /**
         * 读取文件中的数据
         * @param file
         * @return
         */
        public static String read(File file){
            StringBuilder sb = new StringBuilder();
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                try {
                    String str;
                    while ((str = reader.readLine()) != null) {
                        sb.append(str);
                        sb.append("\n");
                    }
                } finally {
                    reader.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return sb.toString();
        }
    
        public static String read(String filename) {
            return read(new File(filename).getAbsoluteFile());
        }
    
        /**
         * 读取二进制文件
         * @param bfile:待读取数据的文件
         * @return:一个包含文件内容的字节数组
         */
        public static byte[] readByte(File bfile)throws IOException{
            try {
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(bfile));
                try {
                    byte[] bytes = new byte[in.available()];
                    in.read(bytes);
                    return bytes;
                }finally {
                    in.close();
                }
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    
        public static byte[] readByte(String bfn) throws IOException{
            return readByte(new File(bfn).getAbsoluteFile());
        }
    
        /**
         * 将数据写入文件
         * @param file
         * @param content
         */
        public static void write(File file, String content){
            try {
                PrintWriter writer = new PrintWriter(file);
                try {
                    writer.println(content);
                }finally {
                    writer.close();
                }
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
    
        public static void write(String filename, String content){
            write(new File(filename).getAbsoluteFile(), content);
        }
    }
    

    相关文章

      网友评论

        本文标题:Java I/O (二)--I/O流的使用

        本文链接:https://www.haomeiwen.com/subject/vigkettx.html