java 无损读取文本文件

来源:互联网 发布:网络课程培训小结 编辑:程序博客网 时间:2024/05/01 13:50

java 如何无损读取文本文件呢?

以下是有损

Java代码  收藏代码
  1. @Deprecated  
  2.     public static String getFullContent(File file, String charset) {  
  3.         BufferedReader reader = null;  
  4.         if (!file.exists()) {  
  5.             System.out.println("getFullContent: file(" + file.getAbsolutePath()  
  6.                     + ") does not exist.");  
  7.             return null;  
  8.         }  
  9.         if (charset == null) {  
  10.             charset = SystemHWUtil.CHARSET_ISO88591;  
  11.         }  
  12.         try {  
  13.             reader = getBufferReaderFromFile(file, charset);  
  14.             return getFullContent(reader);  
  15.         } catch (FileNotFoundException e1) {  
  16.             e1.printStackTrace();  
  17.         } finally {  
  18.             if (null != reader) {  
  19.                 try {  
  20.                     reader.close();  
  21.                 } catch (IOException e) {  
  22.                     e.printStackTrace();  
  23.                 }  
  24.             }  
  25.         }  
  26.         return null;  
  27.     }  
  28.   
  29. public static BufferedReader getBufferReaderFromFile(File file,  
  30.             String charset) throws FileNotFoundException {  
  31.         InputStream ss = new FileInputStream(file);  
  32.         InputStreamReader ireader;  
  33.         BufferedReader reader = null;  
  34.         try {  
  35.             if (charset == null) {  
  36.                 ireader = new InputStreamReader(ss,  
  37.                         SystemHWUtil.CHARSET_ISO88591);  
  38.             } else {  
  39.                 ireader = new InputStreamReader(ss, charset);  
  40.             }  
  41.             reader = new BufferedReader(ireader);  
  42.         } catch (UnsupportedEncodingException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.   
  46.         return reader;  
  47.     }  
  48.   
  49. /** 
  50.      * have closed reader 
  51.      *  
  52.      * @param reader 
  53.      * @return 
  54.      */  
  55.     @Deprecated  
  56.     public static String getFullContent(BufferedReader reader) {  
  57.         StringBuilder sb = new StringBuilder();  
  58.         String readedLine = null;  
  59.         try {  
  60.             while ((readedLine = reader.readLine()) != null) {  
  61.                 sb.append(readedLine);  
  62.                 sb.append(SystemHWUtil.CRLF);  
  63.             }  
  64.         } catch (IOException e) {  
  65.             e.printStackTrace();  
  66.         } finally {  
  67.             try {  
  68.                 reader.close();  
  69.             } catch (IOException e) {  
  70.                 e.printStackTrace();  
  71.             }  
  72.         }  
  73.         String content = sb.toString();  
  74.         int length_CRLF = SystemHWUtil.CRLF.length();  
  75.         if (content.length() <= length_CRLF) {  
  76.             return content;  
  77.         }  
  78.         return content.substring(0, content.length() - length_CRLF);//  
  79.     }  

 测试:

Java代码  收藏代码
  1. @Test  
  2.     public void test_getFullContent(){  
  3.         String filepath="D:\\bin\\config\\conf_passwd.properties";  
  4.         try {  
  5.             InputStream in =new FileInputStream(filepath);  
  6.             System.out.print(FileUtils.getFullContent(filepath, "UTF-8"));  
  7.         } catch (FileNotFoundException e) {  
  8.             e.printStackTrace();  
  9.         } catch (IOException e) {  
  10.             e.printStackTrace();  
  11.         }  
  12.     }  

 

介绍三种无损读取的方式

方式一:使用InputStreamReader,指定编码

Java代码  收藏代码
  1. /*** 
  2.      * 指定字符编码,无损地读取文本文件. 
  3.      *  
  4.      * @param in 
  5.      *            : 输入流,会关闭 
  6.      * @param charset 
  7.      *            : 字符编码 
  8.      * @return 
  9.      * @throws IOException 
  10.      */  
  11.     public static String getFullContent3(InputStream in, String charset)  
  12.             throws IOException {  
  13.         StringBuffer sbuffer = new StringBuffer();  
  14.         InputStreamReader inReader;  
  15.         //设置字符编码  
  16.         inReader = new InputStreamReader(in, charset);  
  17.         char[] ch = new char[SystemHWUtil.BUFF_SIZE_1024];  
  18.         int readCount = 0;  
  19.         while ((readCount = inReader.read(ch)) != -1) {  
  20.             sbuffer.append(ch, 0, readCount);  
  21.         }  
  22.         inReader.close();  
  23.         in.close();  
  24.         return sbuffer.toString();  
  25.     }  

 测试:

Java代码  收藏代码
  1. @Test  
  2.     public void test_getFullContent3(){  
  3.         String filepath="D:\\bin\\config\\conf_passwd.properties";  
  4.         try {  
  5.             InputStream in =new FileInputStream(filepath);  
  6.             System.out.print(FileUtils.getFullContent3(in, "UTF-8"));  
  7.         } catch (FileNotFoundException e) {  
  8.             e.printStackTrace();  
  9.         } catch (IOException e) {  
  10.             e.printStackTrace();  
  11.         }  
  12.     }  

 

 

方式二:先读取出字节数组,再使用String的构造方法

Java代码  收藏代码
  1. public static String getFullContent4(InputStream in, String charset) throws IOException{  
  2.         byte[]bytes=FileUtils.readBytes3(in);  
  3.         return new String(bytes,charset);  
  4.     }  
  5.   
  6. /*** 
  7.      * Has been tested 
  8.      *  
  9.      * @param in 
  10.      * @return 
  11.      * @throws IOException 
  12.      */  
  13.     public static byte[] readBytes3(InputStream in) throws IOException {  
  14.         BufferedInputStream bufin = new BufferedInputStream(in);  
  15.         int buffSize = BUFFSIZE_1024;  
  16.         ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);  
  17.   
  18.         // System.out.println("Available bytes:" + in.available());  
  19.   
  20.         byte[] temp = new byte[buffSize];  
  21.         int size = 0;  
  22.         while ((size = bufin.read(temp)) != -1) {  
  23.             out.write(temp, 0, size);  
  24.         }  
  25.         bufin.close();  
  26.         in.close();  
  27.         byte[] content = out.toByteArray();  
  28.         out.flush();  
  29.         out.close();  
  30.         return content;  
  31.     }  

 

 

方式三:使用System.arraycopy,所以效率不高,因为有拷贝操作(不推荐

Java代码  收藏代码
  1. public static String getFullContent2(InputStream in, String charset)  
  2.             throws IOException {  
  3.         int step = BUFFSIZE_1024;  
  4.         BufferedInputStream bis = new BufferedInputStream(in);  
  5.   
  6.         // Data's byte array  
  7.         byte[] receData = new byte[step];  
  8.   
  9.         // data length read from the stream  
  10.         int readLength = 0;  
  11.   
  12.         // data Array offset  
  13.         int offset = 0;  
  14.   
  15.         // Data array length  
  16.         int byteLength = step;  
  17.   
  18.         while ((readLength = bis.read(receData, offset, byteLength - offset)) != -1) {  
  19.             // Calculate the current length of the data  
  20.             offset += readLength;  
  21.             // Determine whether you need to copy data , when the remaining  
  22.             // space is less than step / 2, copy the data  
  23.             if (byteLength - offset <= step / 2) {  
  24.                 byte[] tempData = new byte[receData.length + step];  
  25.                 System.arraycopy(receData, 0, tempData, 0, offset);  
  26.                 receData = tempData;  
  27.                 byteLength = receData.length;  
  28.             }  
  29.         }  
  30.   
  31.         return new String(receData, 0, offset, charset);  
  32.     }  

 

总结:推荐使用方式一方式二

相关方法见附件中com.io.hw.file.util.FileUtils类

0 0