Java IO使用总结

Posted Shen_JC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java IO使用总结相关的知识,希望对你有一定的参考价值。

最近在写android网络操作的时候突然发现竟然不知道怎么写IO操作了。于是找了一下印象笔记,居然没有收藏过关于IO相关的笔记,那么索性就自己总结一下吧。

字节流

ByteArrayInputStream & ByteArrayOutputStream

ByteArrayInputStream : 把字节数组转化为输入流,。
ByteArrayOutputStream:把内容写入到内部字节数组缓存中,其实就是包含了一个“byte buf[]”数组的OutputStream。当写操作完成之后,可以访问缓存数组的一个备份。

实例:

   public static void testByteArrayStream() 
        String sourceString = "This is a test about ByteArrayOutputStream " +
                "and ByteArrayInputStream";

        try 
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            outputStream.write(sourceString.getBytes());

            byte[] sourceBytes = outputStream.toByteArray();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(sourceBytes);

            // 方法一:一次读取一个字节,只适合占用一个字节的字符串。
            int ch = -1;
            while ((ch = inputStream.read()) != -1) 
                System.out.print((char) ch);
            
            System.out.println("\\n");

            // 方法二:一次读取一个固定长度的数组。
            /*byte[] buffer = new byte[10];
            while (inputStream.read(buffer) != -1) 
                System.out.println(new String(buffer));
            */

            inputStream.close();
            outputStream.close();
         catch (IOException e) 
            e.printStackTrace();
        
    

FileInputStream & FileOutputStream

BufferedInputStream & BufferedOutputStream

FileInputStream 和FileOutputStream是专门用来读写字节文件。由于没有缓存,最好使用BufferedInputStream 和BufferedOutputStream来封装使用它们。所以把他们放在了一起。

Buffered是对InputStream和OutputStream的一个封装,提供一个buffer来缓存input和output,BufferedInputStream 会自动读取固定长度的字符流到buffer中,每次read先从buffer中读取;BufferedOutputStream会把write的字节先放到buffer中,如果超过设置长度才会执行写操作。
这算是以空间来换取时间。

实例:

    public static void testFileInputStream() 
        File from = new File("a.gif");
        File to = new File("b.gif");
        if (from.exists()) 
            FileInputStream fileInputStream = null;
            BufferedInputStream bufferedInputStream = null;
            FileOutputStream fileOutputStream = null;
            BufferedOutputStream bufferedOutputStream = null;

            try 
                fileInputStream = new FileInputStream(from);
                bufferedInputStream = new BufferedInputStream(fileInputStream);

                fileOutputStream = new FileOutputStream(to);
                bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

                byte[] buffer = new byte[1024];

                while (bufferedInputStream.read(buffer) != -1) 
                    bufferedOutputStream.write(buffer);
                
             catch (FileNotFoundException e) 
                e.printStackTrace();
             catch (IOException e) 
                e.printStackTrace();
             finally 
                try 
                    if (bufferedInputStream != null) 
                        bufferedInputStream.close();
                    
                    if (bufferedOutputStream != null) 
                        bufferedInputStream.close();
                    
                 catch (IOException e) 
                    e.printStackTrace();
                
            
         else 
            System.err.println(from.getName() + " 文件不存在!");
        
    

DataInputStream & DataOutputStream

提供读写java的基本数据类型。如writeBoolean(),writeUTF(),writeChar,writeByte(),writeDouble()等和对应的read方法。

实例:

        BufferedOutputStream bufferedOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;

        try 
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
            dataOutputStream = new DataOutputStream(bufferedOutputStream);

            dataOutputStream.writeShort(1);
            dataOutputStream.writeChar(',');
            dataOutputStream.writeInt(20);
            dataOutputStream.writeBoolean(false);
            dataOutputStream.writeChar(',');
            dataOutputStream.writeUTF("Test哦!");

            dataOutputStream.flush();

            bufferedInputStream = new BufferedInputStream(new FileInputStream(new File("out.txt")));
            dataInputStream = new DataInputStream(bufferedInputStream);
            short out1 = dataInputStream.readShort();
            char out2 = dataInputStream.readChar();
            int out3 = dataInputStream.readInt();
            boolean out4 = dataInputStream.readBoolean();
            char out5 = dataInputStream.readChar();
            String out6 = dataInputStream.readUTF();

            System.out.println("Result" + out1 + out2 + out3 + out4 + out5 + out6);

         catch (FileNotFoundException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
         finally 
            try 
                if (bufferedOutputStream != null) 
                    bufferedOutputStream.close();
                

                if (bufferedInputStream != null) 
                    bufferedInputStream.close();
                
             catch (IOException e) 
                e.printStackTrace();
            
        

ObjectInputStream & ObjectOutputStream

读写实现了Serializable接口的对象的字节流。

实例:

        ObjectInputStream objectInputStream = null;
        ObjectOutputStream objectOutputStream = null;

        try 
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("out.txt")));
            objectOutputStream.writeUTF("ObjectStream:");

            Employee employee = new Employee();
            employee.setName("TOM");
            employee.setAge(22);
            employee.setAddress("China");
            employee.setPhoneNumber("987766666");
            objectOutputStream.writeObject(employee);

            objectInputStream = new ObjectInputStream(new FileInputStream(new File("out.txt")));
            String out1 = objectInputStream.readUTF();
            Object out2 = (Employee) objectInputStream.readObject();
            System.out.println(out1 + out2);

         catch (IOException e) 
            e.printStackTrace();
         catch (ClassNotFoundException e) 
            e.printStackTrace();
         finally 
            try 
                objectInputStream.close();
                objectOutputStream.close();
             catch (IOException e) 
                e.printStackTrace();
            
        

字符流

CharArrayReader & CharArrayWriter

CharArrayReader :把字符数组作为一个输入流
CharArrayWriter: CharArrayWriter里面包含一个字符数组来当做缓存,写操作就是把内容写入到缓存中。当写操作完成之后,可以访问缓存数组的一个备份。

实例:

        String sourceString = "This is a test about ByteArrayOutputStream and ByteArrayInputStream";

        CharArrayReader charArrayReader = null;
        CharArrayWriter charArrayWriter = null;

        charArrayWriter = new CharArrayWriter();
        try 
            // 把sourceString写入到CharArrayWriter的缓存数组中
            charArrayWriter.write(sourceString);
         catch (IOException e) 
            e.printStackTrace();
        

        String sourceWriter = charArrayWriter.toString();
        // 把sourceWriter字符串转化为输入流
        charArrayReader = new CharArrayReader(sourceWriter.toCharArray());

        StringBuilder stringBuilder = new StringBuilder();

        // 方法一:一次读取一个字符
    /*    int ch = -1;
        try 
            while ((ch = charArrayReader.read()) != -1) 
                stringBuilder.append((char) ch);
            
            System.out.println("Read one Char: " + stringBuilder.toString());
         catch (IOException e) 
            e.printStackTrace();
         finally 
            charArrayReader.close();
        */

        // 方法二:一次读取一个字符数组
        char[] chars = new char[10];
        int count;
        try 
            while ((count = charArrayReader.read(chars)) != -1) 
                stringBuilder.append(String.copyValueOf(chars, 0, count));
            
            System.out.println("Read char array: " + stringBuilder.toString());
         catch (IOException e) 
            e.printStackTrace();
         finally 
            charArrayReader.close();
        

FileReader & FileWriter

已字符流的形式读写文件。
如果读写操作比较频繁,需要使用BufferedReader和 BufferedWriter来包装使用。

实例:

        FileReader fileReader = null;
        FileWriter fileWriter = null;

        try 
            fileReader = new FileReader(new File("out.txt"));
            fileWriter = new FileWriter(new File("out2.txt"));

            // 读写不频繁的时候,直接使用
            char[] buffer = new char[1024];
            while (fileReader.read(buffer) != -1) 
                fileWriter.write(buffer);
            
         catch (FileNotFoundException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
         finally 
            try 
                if (fileReader != null) 
                    fileReader.close();
                

                if (fileWriter != null) 
                    fileWriter.close();
                
             catch (IOException e) 
                e.printStackTrace();
            
        

BufferedReader & BufferedWriter

自带Buffer的Reader和Write。如果读写操作比较频繁的话,可以使用这两个类。

实例:

       FileReader fileReader = null;
        FileWriter fileWriter = null;

        try 
            fileReader = new FileReader(new File("out.txt"));
            fileWriter = new FileWriter(new File("out2.txt"));

            BufferedReader bufferedReader = new BufferedReader(fileReader);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            String buffer;
            while ((buffer = bufferedReader.readLine()) != null) 
                bufferedWriter.write(buffer);
                bufferedWriter.write('\\n');
            

            bufferedWriter.close();
            bufferedReader.close();
         catch (FileNotFoundException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
         finally 
            try 

                if (fileReader != null) 
                    fileReader.close();

                

                if (fileWriter != null) 
                    fileWriter.close();
                

             catch (IOException e) 
                e.printStackTrace();
            
        

StringReader & StringWriter

StringReader:把String转化为一个流。
StringWriter:带有StringBuffer的Write。

实例:

        String sourceString = "This is a test about ByteArrayOutputStream and ByteArrayInputStream";

        StringReader stringReader = null;
        StringWriter stringWriter = null;

        stringReader = new StringReader(sourceString);
        stringWriter = new StringWriter();

        char[] buffer = new char[1024];
        try 
            while (stringReader.read(buffer) != -1) 
                stringWriter.write(buffer);
            
            System.out.println(stringWriter.toString());
         catch (IOException e) 
            e.printStackTrace();
        

        stringReader.close();
        try 
            stringWriter.close();
         catch (IOException e) 
            e.printStackTrace();
        

以上是关于Java IO使用总结的主要内容,如果未能解决你的问题,请参考以下文章

java中IO及中文乱码问题

Java中的IO学习总结

IO系列之File

java-----NIO总结

IO流总结

Java IO8:IO简单总结