0
点赞
收藏
分享

微信扫一扫

Java一次读取文本文件所有内容


我们做文本处理的时候的最常用的就是读写文件了,尤其是读取文件,不论是什么文件,我都倾向于一次性将文本的原始内容直接读取到内存中再做处理,当然,这需要你有一台大内存的机器,内存不够者……可以一次读取少部分内容,分多次读取。
读取文件效率最快的方法就是一次全读进来,很多人用readline()之类的方法,可能需要反复访问文件,而且每次readline()都会调用编码转换,降低了速度,所以,在已知编码的情况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式,典型的代码如下:

[html]  view plain  copy



/**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }

/**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }

1. public String readToString(String fileName) {  
2. encoding = "ISO-8859-1";  
3. file = new File(fileName);  
4. filelength = file.length();  
5. filecontent = new byte[filelength.intValue()];  
6.         try {  
7. in = new FileInputStream(file);  
8.             in.read(filecontent);  
9.             in.close();  
10.         } catch (FileNotFoundException e) {  
11.             e.printStackTrace();  
12.         } catch (IOException e) {  
13.             e.printStackTrace();  
14.         }  
15.         try {  
16.             return new String(filecontent, encoding);  
17.         } catch (UnsupportedEncodingException e) {  
18.             System.err.println("The OS does not support " + encoding);  
19.             e.printStackTrace();  
20.             return null;  
21.         }  
22.      }  
/**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }



















举报

相关推荐

0 条评论