java读取文件之txt文本

时间:2021-04-21 09:19:40

1.方法一:

public static String txt2String(File file){
13 String result = "";
14 try{
15 BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
16 String s = null;
17 while((s = br.readLine())!=null){//使用readLine方法,一次读一行
18 result = result + "\n" +s;
19 }
20 br.close();
21 }catch(Exception e){
22 e.printStackTrace();
23 }
24 return result;
25 }
26
27 public static void main(String[] args){
28 File file = new File("D:/luceneData/test1.txt");
29 System.out.println(txt2String(file));
30 } 2.方法二:
public static void readTxtFile(String filePath){
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        System.out.println(lineTxt);
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
     
    }
     
    public static void main(String argv[]){
        String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
 
        readTxtFile(filePath);
    }