天天看点

JAVA读取文件的几种方法

喜欢的朋友可以关注下,粉丝也缺。

InputStreamReader+BufferedReader读取字符串

InputStreamReader 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。 

构造方法 : 

    InputStreamReader isr = new InputStreamReader(InputStream in);//构造一个默认编码集的InputStreamReader类 

    InputStreamReader isr = new InputStreamReader(InputStream in,String charsetName);//构造一个指定编码集的InputStreamReader类。 

    参数 in对象通过 InputStream in = System.in;获得。//读取键盘上的数据。 

    或者 InputStream in = new FileInputStream(String fileName);//读取文件中的数据。可以看出 FileInputStream 为InputStream的子类。 

主要方法 :int read();//读取单个字符。 

                 int read(char []cbuf);//将读取到的字符存到数组中。返回读取的字符数。

private static String readString()
    {
        int len=0;
        StringBuffer str=new StringBuffer("");
        File file=new File(FILE_IN);
        try {
            FileInputStream is=new FileInputStream(file);
            InputStreamReader isr= new InputStreamReader(is);
            BufferedReader in= new BufferedReader(isr);
            String line=null;
            while( (line=in.readLine())!=null )
            {
                if(len != 0)  // 处理换行符的问题
                {
                    str.append("\r\n"+line);
                }
                else
                {
                    str.append(line);
                }
                len++;
            }
            in.close();
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
 }
        return str.toString();
    }           

 FileReader 读取

FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 

File

 或 

Blob

 对象指定要读取的文件或数据。

其中File对象可以是来自用户在一个

<input>

元素上选择文件后返回的

FileList

对象,也可以来自拖放操作生成的 

DataTransfer

对象,还可以是来自在一个

HTMLCanvasElement

上执行

mozGetAsFile()方法后返回结果

.

private static String readString()
    {
        StringBuffer str=new StringBuffer("");
        File file=new File(FILE_IN);
        try {
            FileReader fr=new FileReader(file);
            int ch = 0;
            while((ch = fr.read())!=-1 )
            {
                System.out.print((char)ch+" "); 
            }
            fr.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("File reader出错");
        }
        return str.toString();
    }           

以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

 当然也是可以读字符串的。

/* 貌似是说网络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/
    public String readString1()
    {
        try
        {
            //FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。 
            FileInputStream inStream=this.openFileInput(FILE_NAME);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int length=-1;
            while( (length = inStream.read(buffer) != -1)
            {
                bos.write(buffer,0,length);
                // .write方法 SDK 的解释是 Writes count bytes from the byte array buffer starting at offset index to this stream.
                //  当流关闭以后内容依然存在
            }
            bos.close();
            inStream.close();
            return bos.toString();   
            // 为什么不一次性把buffer得大小取出来呢?为什么还要写入到bos中呢? return new(buffer,"UTF-8") 不更好么?
            // return new String(bos.toByteArray(),"UTF-8");       
        }
    }           

按字节读取字符串

private static String readString3()
{
    String str="";
    File file=new File(FILE_IN);
    try {
        FileInputStream in=new FileInputStream(file);
        // size  为字串的长度 ,这里一次性读完
        int size=in.available();
        byte[] buffer=new byte[size];
        in.read(buffer);
        in.close();
        str=new String(buffer,"GB2312");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        return null;
        e.printStackTrace();
    }
    return str;
}           

如遇到问题欢迎进群308742428