1 package com.campu;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedReader;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.InputStreamReader;
8 import java.io.Reader;
9
10 /**
11 * @author 码农小江
12 * H20121012.java
13 * 2012-10-12下午11:40:21
14 */
15 public class H20121012 {
16 /**
17 * 功能:Java读取txt文件的内容
18 * 步骤:1:先获得文件句柄
19 * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
20 * 3:读取到输入流后,需要读取生成字节流
21 * 4:一行一行的输出。readline()。
22 * 备注:需要考虑的是异常情况
23 * @param filePath
24 */
25 public static void readTxtFile(String filePath){
26 try {
27 String encoding="GBK";
28 File file=new File(filePath);
29 if(file.isFile() && file.exists()){ //判断文件是否存在
30 InputStreamReader read = new InputStreamReader(
31 new FileInputStream(file),encoding);//考虑到编码格式
32 BufferedReader bufferedReader = new BufferedReader(read);
33 String lineTxt = null;
34 while((lineTxt = bufferedReader.readLine()) != null){
35 System.out.println(lineTxt);
36 }
37 read.close();
38 }else{
39 System.out.println("找不到指定的文件");
40 }
41 } catch (Exception e) {
42 System.out.println("读取文件内容出错");
43 e.printStackTrace();
44 }
45
46 }
47
48 public static void main(String argv[]){
49 String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
50 // "res/";
51 readTxtFile(filePath);
52 }
53
54
55
56 }