50. in.close();
51. } catch (IOException e1) {
52. }
53. }
54. }
55. }
56.
57. /**
58. *
以字符为单位读取文件,常用于读文本,数字等类型的文件
59. *
60. * @param fileName
61. *
文件名
62. */
63. public static void readFileByChars(String fileName) {
64. File file = new File(fileName);
65. Reader reader = null;
66. try {
67. System.out.println("以字符为单位读取文件内容,一次读一个字节:");
68. //
一次读一个字符
69. reader = new InputStreamReader(new FileInputStream(file));
70. int tempchar;
71. while ((tempchar = reader.read()) != -1) {
72. // 对于 windows 下,\r\n
这两个字符在一起时,表示一个换行。
73. //
但如果这两个字符分开显示时,会换两次行。
74. // 因此,屏蔽掉\r,或者屏蔽\n
。否则,将会多出很多空行。
75. if (((char) tempchar) != '\r') {
76. System.out.print((char) tempchar);
77. }
78. }
79. reader.close();
80. } catch (Exception e) {
81. e.printStackTrace();
82. }
83. try {
84. System.out.println("以字符为单位读取文件内容,一次读多个字节:");
85. //
一次读多个字符
86. char[] tempchars = new char[30];
87. int charread = 0;
88. reader = new InputStreamReader(new FileInputStream(fileName));
89. // 读入多个字符到字符数组中,charread
为一次读取字符数
90. while ((charread = reader.read(tempchars)) != -1) {
91. // 同样屏蔽掉\r
不显示
92. if ((charread == tempchars.length)
93. && (tempchars[tempchars.length - 1] != '\r')) {
94. System.out.print(tempchars);
95. } else {
96. for (int i = 0; i < charread; i++) {
97. if (tempchars[i] == '\r') {
98. continue;
99. } else {
100. System.out.print(tempchars[i]);
101. }
102. }
103. }
104. }
105.
106. } catch (Exception e1) {
107. e1.printStackTrace();