文章标题

来源:互联网 发布:mac winebottler msi 编辑:程序博客网 时间:2024/06/06 14:22

使用字节流InputStream和OutputStream读写文件数据

字节流InputStream和OutputStream读写数据都是通过字节,read()每次读一个字节,write(int n)可以写入指定字节。
read()的使用:

/* * 从文件读出数据 */public void inputStreamFile(){    File file = new File("files" + File.separator + "streamFile.txt");    //先判断文件是否存在    if(!file.exists())        throw new RuntimeException("要读取的文件不存在");    else        System.out.print("读取数据: ");    //文件字节输入流    FileInputStream fis;    try {        fis = new FileInputStream(file);        //length()方法返回的是字节数        int fileLength = (int)file.length();        //构建字节数组,长度等于整个文件的字节数        byte[] b = new byte[fileLength];        //临时整形变量,保存read()方法返回的整形值        int temp;        //字节数组下标变量        int len = 0;        /*         * 一个字节一个字节的读取数据         */        try {            while((temp = fis.read()) != -1){                b[len ++] = (byte)temp;                             }               //输出文件内容                System.out.print(new String(b));                //关闭输出流            fis.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    } catch (FileNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }}write的使用:/* * 往文件写入数据 */public static void outputStreamFile(){    //创建写出文件字节流缓冲区    FileOutputStream fos;    try {        fos = new FileOutputStream(file);        //inputConsoleData是从键盘接收数据        String data = inputConsoleData();        System.out.println("outputStreamFile: " + data);        /*         * 使用FileOutputStream写入文件,FileOutputStream的write()方法只接受byte[]类型          * 的参数,所以需要将string通过getBytes()方法转换为字节数组。         */        byte[] bytesArray = data.getBytes();        try {            fos.write(bytesArray);            fos.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }           } catch (FileNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }} /* * 从键盘输入数据 */public static String inputConsoleData(){    Scanner scanner = new Scanner(System.in);    System.out.print("输入数据:");    String data = scanner.nextLine();    scanner.close();    return data;}
原创粉丝点击