将文件中的内容读到内存中

File  没有读的能力,他只是一个文件对象,需要借助FileInputstream,如果内容很多,则需要建一个缓存,byte【1024】就是缓冲区

package h15;

import java.io.*;

public class FileDemo1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        File f = new File("e:/aa.txt");
        FileInputStream fis = null;
        try {
             fis= new FileInputStream(f);
             byte[] bytes = new byte[1024];
             int n;
             while((n=fis.read(bytes))!=-1){
                 String s = new String(bytes,0,n);
                 System.out.print(s);
             }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

 

posted on 2015-06-14 13:45  编世界  阅读(919)  评论(0编辑  收藏  举报