JAVA读取文件方法大全

简介:
复制代码
  1 public class ReadFromFile {
  2     /**
  3      * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
  4      */
  5     public static void readFileByBytes(String fileName) {
  6         File file = new File(fileName);
  7         InputStream in = null;
  8         try {
  9             System.out.println("以字节为单位读取文件内容,一次读一个字节:");
 10             // 一次读一个字节
 11             in = new FileInputStream(file);
 12             int tempbyte;
 13             while ((tempbyte = in.read()) != -1) {
 14                 System.out.write(tempbyte);
 15             }
 16             in.close();
 17         } catch (IOException e) {
 18             e.printStackTrace();
 19             return;
 20         }
 21         try {
 22             System.out.println("以字节为单位读取文件内容,一次读多个字节:");
 23             // 一次读多个字节
 24             byte[] tempbytes = new byte[100];
 25             int byteread = 0;
 26             in = new FileInputStream(fileName);
 27             ReadFromFile.showAvailableBytes(in);
 28             // 读入多个字节到字节数组中,byteread为一次读入的字节数
 29             while ((byteread = in.read(tempbytes)) != -1) {
 30                 System.out.write(tempbytes, 0, byteread);
 31             }
 32         } catch (Exception e1) {
 33             e1.printStackTrace();
 34         } finally {
 35             if (in != null) {
 36                 try {
 37                     in.close();
 38                 } catch (IOException e1) {
 39                 }
 40             }
 41         }
 42     }
 43 
 44     /**
 45      * 以字符为单位读取文件,常用于读文本,数字等类型的文件
 46      */
 47     public static void readFileByChars(String fileName) {
 48         File file = new File(fileName);
 49         Reader reader = null;
 50         try {
 51             System.out.println("以字符为单位读取文件内容,一次读一个字节:");
 52             // 一次读一个字符
 53             reader = new InputStreamReader(new FileInputStream(file));
 54             int tempchar;
 55             while ((tempchar = reader.read()) != -1) {
 56                 // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
 57                 // 但如果这两个字符分开显示时,会换两次行。
 58                 // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
 59                 if (((char) tempchar) != '\r') {
 60                     System.out.print((char) tempchar);
 61                 }
 62             }
 63             reader.close();
 64         } catch (Exception e) {
 65             e.printStackTrace();
 66         }
 67         try {
 68             System.out.println("以字符为单位读取文件内容,一次读多个字节:");
 69             // 一次读多个字符
 70             char[] tempchars = new char[30];
 71             int charread = 0;
 72             reader = new InputStreamReader(new FileInputStream(fileName));
 73             // 读入多个字符到字符数组中,charread为一次读取字符数
 74             while ((charread = reader.read(tempchars)) != -1) {
 75                 // 同样屏蔽掉\r不显示
 76                 if ((charread == tempchars.length)
 77                         && (tempchars[tempchars.length - 1] != '\r')) {
 78                     System.out.print(tempchars);
 79                 } else {
 80                     for (int i = 0; i < charread; i++) {
 81                         if (tempchars[i] == '\r') {
 82                             continue;
 83                         } else {
 84                             System.out.print(tempchars[i]);
 85                         }
 86                     }
 87                 }
 88             }
 89 
 90         } catch (Exception e1) {
 91             e1.printStackTrace();
 92         } finally {
 93             if (reader != null) {
 94                 try {
 95                     reader.close();
 96                 } catch (IOException e1) {
 97                 }
 98             }
 99         }
100     }
101 
102     /**
103      * 以行为单位读取文件,常用于读面向行的格式化文件
104      */
105     public static void readFileByLines(String fileName) {
106         File file = new File(fileName);
107         BufferedReader reader = null;
108         try {
109             System.out.println("以行为单位读取文件内容,一次读一整行:");
110             reader = new BufferedReader(new FileReader(file));
111             String tempString = null;
112             int line = 1;
113             // 一次读入一行,直到读入null为文件结束
114             while ((tempString = reader.readLine()) != null) {
115                 // 显示行号
116                 System.out.println("line " + line + ": " + tempString);
117                 line++;
118             }
119             reader.close();
120         } catch (IOException e) {
121             e.printStackTrace();
122         } finally {
123             if (reader != null) {
124                 try {
125                     reader.close();
126                 } catch (IOException e1) {
127                 }
128             }
129         }
130     }
131 
132     /**
133      * 随机读取文件内容
134      */
135     public static void readFileByRandomAccess(String fileName) {
136         RandomAccessFile randomFile = null;
137         try {
138             System.out.println("随机读取一段文件内容:");
139             // 打开一个随机访问文件流,按只读方式
140             randomFile = new RandomAccessFile(fileName, "r");
141             // 文件长度,字节数
142             long fileLength = randomFile.length();
143             // 读文件的起始位置
144             int beginIndex = (fileLength > 4) ? 4 : 0;
145             // 将读文件的开始位置移到beginIndex位置。
146             randomFile.seek(beginIndex);
147             byte[] bytes = new byte[10];
148             int byteread = 0;
149             // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
150             // 将一次读取的字节数赋给byteread
151             while ((byteread = randomFile.read(bytes)) != -1) {
152                 System.out.write(bytes, 0, byteread);
153             }
154         } catch (IOException e) {
155             e.printStackTrace();
156         } finally {
157             if (randomFile != null) {
158                 try {
159                     randomFile.close();
160                 } catch (IOException e1) {
161                 }
162             }
163         }
164     }
165 
166     /**
167      * 显示输入流中还剩的字节数
168      */
169     private static void showAvailableBytes(InputStream in) {
170         try {
171             System.out.println("当前字节输入流中的字节数为:" + in.available());
172         } catch (IOException e) {
173             e.printStackTrace();
174         }
175     }
176 
177     public static void main(String[] args) {
178         String fileName = "C:/temp/newTemp.txt";
179         ReadFromFile.readFileByBytes(fileName);
180         ReadFromFile.readFileByChars(fileName);
181         ReadFromFile.readFileByLines(fileName);
182         ReadFromFile.readFileByRandomAccess(fileName);
183     }
184 }
复制代码

 



本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/3805667.html,如需转载请自行联系原作者

相关文章
|
2月前
|
前端开发 JavaScript Java
Java 开发中 Swing 界面嵌入浏览器实现方法详解
摘要:Java中嵌入浏览器可通过多种技术实现:1) JCEF框架利用Chromium内核,适合复杂网页;2) JEditorPane组件支持简单HTML显示,但功能有限;3) DJNativeSwing-SWT可内嵌浏览器,需特定内核支持;4) JavaFX WebView结合Swing可完美支持现代网页技术。每种方案各有特点,开发者需根据项目需求选择合适方法,如JCEF适合高性能要求,JEditorPane适合简单展示。(149字)
296 1
|
1月前
|
算法 Java 开发者
Java 项目实战数字华容道与石头迷阵游戏开发详解及实战方法
本文介绍了使用Java实现数字华容道和石头迷阵游戏的技术方案与应用实例,涵盖GUI界面设计、二维数组操作、游戏逻辑控制及自动解法算法(如A*),适合Java开发者学习游戏开发技巧。
191 46
|
2月前
|
Java 索引
Java ArrayList中的常见删除操作及方法详解。
通过这些方法,Java `ArrayList` 提供了灵活而强大的操作来处理元素的移除,这些方法能够满足不同场景下的需求。
380 30
|
2月前
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
186 14
|
2月前
|
安全 Java API
Java 17 及以上版本核心特性在现代开发实践中的深度应用与高效实践方法 Java 开发实践
本项目以“学生成绩管理系统”为例,深入实践Java 17+核心特性与现代开发技术。采用Spring Boot 3.1、WebFlux、R2DBC等构建响应式应用,结合Record类、模式匹配、Stream优化等新特性提升代码质量。涵盖容器化部署(Docker)、自动化测试、性能优化及安全加固,全面展示Java最新技术在实际项目中的应用,助力开发者掌握现代化Java开发方法。
126 1
|
2月前
|
安全 Java API
Java 集合高级应用与实战技巧之高效运用方法及实战案例解析
本课程深入讲解Java集合的高级应用与实战技巧,涵盖Stream API、并行处理、Optional类、现代化Map操作、不可变集合、异步处理及高级排序等核心内容,结合丰富示例,助你掌握Java集合的高效运用,提升代码质量与开发效率。
203 0
|
2月前
|
算法 搜索推荐 Java
Java中的Collections.shuffle()方法及示例
`Collections.shuffle()` 是 Java 中用于随机打乱列表顺序的方法,基于 Fisher-Yates 算法实现,支持原地修改。可选传入自定义 `Random` 对象以实现结果可重复,适用于抽奖、游戏、随机抽样等场景。
120 0
|
2月前
|
安全 Java
JAVA:Collections类的shuffle()方法
`Collections.shuffle()` 是 Java 中用于随机打乱列表顺序的工具方法,适用于洗牌、抽奖等场景。该方法直接修改原列表,支持自定义随机数生成器以实现可重现的打乱顺序。使用时需注意其原地修改特性及非线程安全性。
130 0
|
2月前
|
算法 安全 Java
java中Collections.shuffle方法的功能说明
`Collections.shuffle()` 是 Java 中用于随机打乱列表顺序的方法,基于 Fisher-Yates 算法实现,常用于洗牌、抽奖等场景。可选 `Random` 参数支持固定种子以实现可重复的随机顺序。方法直接修改原列表,无返回值。
120 0
|
2月前
|
Java 程序员 项目管理
Java 程序员不容错过的 Git Flow 全套学习资料及应用方法详解 Git Flow
本文详细介绍了Git Flow技术方案及其在Java项目中的应用实例,涵盖分支管理、版本发布与紧急修复流程,帮助开发者掌握高效的代码管理方法,提升团队协作效率。附示例操作及代码下载链接。
80 0