background image

108.        } finally {   
109.            if (reader != null) {   

110.                try {   
111.                    reader.close();   

112.                } catch (IOException e1) {   
113.                }   

114.            }   
115.        }   

116.    }   
117.  

118.    /**  
119.     * 

  

以行为单位读取文件,常用于读面向行的格式化文件

120.     *   
121.     * @param fileName  

122.     *            

  

文件名

123.     */  

124.    public static void readFileByLines(String fileName) {   
125.        File file = new File(fileName);   

126.        BufferedReader reader = null;   
127.        try {   

128.            System.out.println("以行为单位读取文件内容,一次读一整行:");   
129.            reader = new BufferedReader(new FileReader(file));   

130.            String tempString = null;   
131.            int line = 1;   

132.            // 一次读入一行,直到读入 null

   

为文件结束

133.            while ((tempString = reader.readLine()) != null) {   

134.                // 

   

显示行号

135.                System.out.println("line " + line + ": " + tempString);   

136.                line++;   
137.            }   

138.            reader.close();   
139.        } catch (IOException e) {   

140.            e.printStackTrace();   
141.        } finally {   

142.            if (reader != null) {   
143.                try {   

144.                    reader.close();   
145.                } catch (IOException e1) {   

146.                }   
147.            }   

148.        }   
149.    }   

150.  
151.    /**  

152.     * 

  

随机读取文件内容

153.     *   

154.     * @param fileName  
155.     *            

  

文件名

156.     */  
157.    public static void readFileByRandomAccess(String fileName) {   

158.        RandomAccessFile randomFile = null;   
159.        try {   

160.            System.out.println("随机读取一段文件内容:");   
161.            // 

   

打开一个随机访问文件流,按只读方式

162.            randomFile = new RandomAccessFile(fileName, "r");   
163.            // 

   

文件长度,字节数

164.            long fileLength = randomFile.length();   
165.            // 

   

读文件的起始位置