• Java当中的IO(2)


    1、大文件的读写方法

    代码: 

    //第一步:导入类
    import java.io.*;
    
    class Test{
        public static void main(String args[]){
            //声明输入流引用
            FileInputStream fis = null;
            //声明输出流引用
            FileOutputStream fos = null;
            try{
                //生成代表输入流的对象
                fis = new FileInputStream("e:/src/from.txt");
                //生成代表输出流的对象
                fos = new FileOutputStream("e:/src/to.txt");
                
                //生成一个字节数组,每次读取1024字节
                byte[] buffer = new byte[1024];
                while(true){
                    //调用输入流对象的read方法,读取数据
                    int temp = fis.read(buffer,0,buffer.length);
                    if(temp==-1){
                        break;
                    }
                    //调用输出流对象的write方法,写入数据
                    fos.write(buffer,0,temp);
                }
            }
            catch(Exception e){
                System.out.println(e);
            }
            finally{
                try{
                    //关闭输入、输出流
                    fis.close();
                    fos.close();
                }
                catch(Exception e){
                    System.out.println(e);
                }
            }
        }
    }

    2、字符流的使用方法:

      字符流:读写文件时,以字符为基础

      字符输入流:Reader <-- FileReader

        int read(char[] c,int off,int len)

      字符输出流:Writer  <-- FileWriter

        void write(char[] c,int off,int len)

    代码:

    //第一步,导入类
    import java.io.*;
    
    class TestChar{
        public static void main(String args[]){
            //声明一个输入字符流的引用
            FileReader fr = null;
            //声明一个输出字符流的引用
            FileWrter  fw = null;
            try{
                //生成对象
                fr = new FileReader("e:/src/from.txt");
                fw = new FileWriter("e:/src/to.txt");
                
                //声明一个字符数组
                char []  buffer = new char[100];
                int temp = fr.read(buffer,0,buffer.length);
                fw.write(buffer,0,temp);
            }catch(Exception e){
                System.out.println(e);
            }
            finally{
                try{
                    fr.close();
                    fw.close();
                }catch(Exception e){
                    System.out.println(e);
                }
            }
        }
    }
  • 相关阅读:
    c#結合正則表達式驗證輸入的字符串
    [SQL]数据库设计说明书模板
    如何在网页中插入Flv视频文件
    JAVASCRIPT常用检验代码
    Javascript知识精华
    提高Remoting的DataSet传输的性能
    如何快速的在SharePoint里构建一个Blog站点
    可爱的 Python,可爱的.NET
    郁闷的Xml Serialization BUG
    初试Zope(1)
  • 原文地址:https://www.cnblogs.com/mdorg/p/3219266.html
Copyright © 2020-2023  润新知