java 无损读取文本文件

简介:

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.     }  
相关文章
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
122 5
实现Java语言的文件断点续传功能的技术方案。
像这样,我们就完成了一项看似高科技、实则亲民的小工程。这样的技术实现不仅具备实用性,也能在面对网络不稳定的挑战时,稳稳地、不失乐趣地完成工作。
48 0
|
8月前
|
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
173 9
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
212 2
|
8月前
|
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
541 5
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
1427 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
解锁“分享文件”高效密码:探秘 Java 二叉搜索树算法
在信息爆炸的时代,文件分享至关重要。二叉搜索树(BST)以其高效的查找性能,为文件分享优化提供了新路径。本文聚焦Java环境下BST的应用,介绍其基础结构、实现示例及进阶优化。BST通过有序节点快速定位文件,结合自平衡树、多线程和权限管理,大幅提升文件分享效率与安全性。代码示例展示了文件插入与查找的基本操作,适用于大规模并发场景,确保分享过程流畅高效。掌握BST算法,助力文件分享创新发展。
深潜数据海洋:Java文件读写全面解析与实战指南
通过本文的详细解析与实战示例,您可以系统地掌握Java中各种文件读写操作,从基本的读写到高效的NIO操作,再到文件复制、移动和删除。希望这些内容能够帮助您在实际项目中处理文件数据,提高开发效率和代码质量。
119 4
|
7月前
|
java实现从HDFS上下载文件及文件夹的功能,以流形式输出,便于用户自定义保存任何路径下
java实现从HDFS上下载文件及文件夹的功能,以流形式输出,便于用户自定义保存任何路径下
220 34
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等