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与多模态AI:构建支持文本、图像和音频的智能应用
随着大模型从单一文本处理向多模态能力演进,现代AI应用需要同时处理文本、图像、音频等多种信息形式。本文深入探讨如何在Java生态中构建支持多模态AI能力的智能应用。我们将完整展示集成视觉模型、语音模型和语言模型的实践方案,涵盖从文件预处理、多模态推理到结果融合的全流程,为Java开发者打开通往下一代多模态AI应用的大门。
835 41
|
Java
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
437 9
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
1422 5
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
709 2
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
523 1
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
4371 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
704 14
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
1081 5
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
495 0