Java中的IO操作

@

JAVA IO

Java IO简洁

IO也写作"I/O",可以理解为In和Out,即输入与输出.
所以,IO体系的基本功能就是:读和写.

IO流
作用:读写设备上的数据,硬盘文件、内存、键盘、网络...

根据数据的走向,可分为:输入流、输出流
根据处理的数据类型,可分为:字节流、字符流

字节流与字符流:

字节流可以处理所有类型的数据,如MP3、图片、文字、视频等.在读取时,读到一个字节就返回一个字节.
在java中对于的类都已"Stream"结尾.

字符流仅能够处理纯文本数据,如txt文本等.在读取时,读取一个或者多个字节,先查找指定的编码表,然后将查到的字符返回.
在java中对应的类都以"Reader"或"Writer"结尾.

字符、字节与编码

字节(Byte)
字节是通过网络传输信息或在硬盘或内存中存储信息的单位,是计算机信息技术用于计量存储容量和传输容量的一种计量单位.
1个字节等于8位二进制,即一个8位的二进制数,是一个很具体的存储空间.
如0x01,0x45,0xFA,……

字符(Char)
字符是人们使用的记号,抽象意义上的一个符号.
如'l','中','a','$',……

字符集(Charset)
"字符集"也称作"编码".
ANSI编码标准所规定的内容包含两层含义:
1.使用哪些字符.也就是说哪些汉子,字母和符号会被收入标准中.所包含"字符"的集合就叫做"字符集".
2.规定每个"字符"分别用一个字节还是多个字节存储,用哪些字节来存储,这个规定就叫做"编码".

使用字节流读写数据

使用FileInputStream和FileOutputStream字节流拷贝文件。

package com.xc.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadByteStream {

    public static void main(String[] args) {
        try {
//            String filePath = new ReadByteStream().getClass().getClassLoader().getResource("text.txt").getPath();//获取文件路径
            String file = new ReadByteStream().getClass().getClassLoader().getResource("text.txt").getFile();//获取文件

            FileInputStream fis = new FileInputStream(file) ;
            byte[] input = new byte[22];
            fis.read(input);

            String inputString = new String(input,"UTF-8");
            System.out.println(inputString);

            fis.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.xc.test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class WriteByteStream {

    public static void main(String[] args) {
        try {
//            String fileName = new ReadByteStream().getClass().getClassLoader().getResource("textw.txt").getPath();//获取文件路径
//            String file = new ReadByteStream().getClass().getClassLoader().getResource("textw.txt").getFile();//获取文件
            String filePath = "D:/loc-test/abc.txt" ;

            String outString = "write 123456写出数据";
            byte[] output = outString.getBytes("UTF-8");

            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(output);

            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.xc.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyByByteStream {

    public static void main(String[] args) {
        //            String filePath = new ReadByteStream().getClass().getClassLoader().getResource("text.txt").getPath();//获取文件路径
        String file = new ReadByteStream().getClass().getClassLoader().getResource("ani.gif").getFile();//获取文件
        String newFilePath = "D:/loc-test/ani_new.gif";

        try {
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(newFilePath);

            byte[] input = new byte[50];
            while (fis.read(input) != -1) {
                fos.write(input);
            }
            System.out.println("done");

            fis.close();
            fos.close();

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

    }
}

使用带缓冲的字节流读写数据

使用BufferedInputStream和BufferedOutputStream缓冲字节流拷贝文件。

package com.xc.test;

import java.io.*;

public class ReadByBufferedByteStream {

    public static void main(String[] args) {
        try {
            String file = new ReadByteStream().getClass().getClassLoader().getResource("test/movie.mp4").getFile();//获取文件
            String newFilePath = "D:/loc-test/movie_new.mp4";

            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis,1024*100);
            FileOutputStream fos = new FileOutputStream(newFilePath);
            BufferedOutputStream bos = new BufferedOutputStream(fos,1024*100);

            long before = System.currentTimeMillis();
            byte[] input = new byte[1024*100];//大型文件对于的数组可以大一些,小文件对于的数组小一些
            int count = 0;
            while (bis.read(input) != -1) {
                bos.write(input);
                count++;
            }
            System.out.println(System.currentTimeMillis() - before + "ms");
            System.out.println("读取了:" + count + "次");

            bis.close();
            fis.close();
            bos.close();
            fos.close();

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

使用字符流读写数据

使用InputStreamReader语OutputStreamWriter字符流读写文件数据。

package com.xc.test;


import java.io.*;

public class RWByCharStream {

    public static void main(String[] args) {

        try {
            String file = new ReadByteStream().getClass().getClassLoader().getResource("test/java.txt").getFile();//获取文件
            String newFilePath = "D:/loc-test/java_new.txt";

            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            FileOutputStream fos = new FileOutputStream(newFilePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");

            char[] input = new char[100];
            int l = 0;
            while ((l = isr.read(input)) != -1) {
//                System.out.println(new String(input, 0, l));
                osw.write(input, 0, l);
            }

            isr.close();
            fis.close();
            osw.close();
            fos.close();
            System.out.println("done");

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

    }
}

使用带有缓冲的字符流读写数据

使用BufferedReader语BufferedWriter缓冲字符流读写文件数据。

package com.xc.test;


import java.io.*;

public class RWByBufferedCharStream {

    public static void main(String[] args) {

        try {
            String file = new ReadByteStream().getClass().getClassLoader().getResource("test/java.txt").getFile();//获取文件
            String newFilePath = "D:/loc-test/java_new_buff.txt";

            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            FileOutputStream fos = new FileOutputStream(newFilePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
//            BufferedWriter bw = new BufferedWriter(osw);
//            PrintWriter pw = new PrintWriter(osw);
            PrintWriter pw = new PrintWriter(osw, true);//autoFlush

            String input;
            while ((input = br.readLine()) != null) {
//                bw.write(input);//无换行符
                pw.println(input);//有换行符
            }


            br.close();
            isr.close();
            fis.close();
//            pw.flush();//强制输出所有缓冲区内容,保证文件的完整
            pw.close();
//            bw.flush();
//            bw.close();
            osw.close();
            fos.close();
            System.out.println("done");

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

    }
}

FileReader与FileWriter

FileReader与FileWriter直接操作文件数据流,并包装为缓冲流进行文件拷贝。

package com.xc.test;

import java.io.*;

public class FileReaderWriter {

    public static void main(String[] args) {
        try {
            String file = new ReadByteStream().getClass().getClassLoader().getResource("test/java.txt").getFile();//获取文件
            String newFilePath = "D:/loc-test/java_new.txt";

            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            FileWriter fw = new FileWriter(newFilePath);
            BufferedWriter bw = new BufferedWriter(fw);

            String line;
            while((line = br.readLine())!=null){
                bw.write(line+"
");
            }

            br.close();
            fr.close();
            bw.flush();
            bw.close();
            fw.close();
            System.out.println("done");

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

    }
}

RandomAccessFile随机文件读写

使用RandomAccessFile可以读写文件的任意位置,一般用于多线程读写操作。

// TODO

使用Apache IO库操作IO与文件

使用Apache IO库操作IO与文件,Apache IO库是一个强大的IO操作库,提供了对于IO与文件大量精简高效的操作方法,文件的读写、拷贝有时候仅需一行代码就可完成。

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
package com.xc.test;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class TestFileUtils {

    public static void main(String[] args) {
        try {

            String file = new ReadByteStream().getClass().getClassLoader().getResource("test/java.txt").getFile();//获取文件

//            String input = FileUtils.readFileToString(new File(file), "UTF-8");
//            System.out.println(input);

            String newFilePath = "D:/loc-test/java_new_apache.txt";
            FileUtils.copyFile(new File(file),new File(newFilePath));

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

}
原文地址:https://www.cnblogs.com/ooo0/p/10744560.html