当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java读取文本文件实例
发布时间:2010/7/28 11:54:03 来源:城市学习网 编辑:ziteng
  1 import java.io.BufferedReader;
  2 import java.io.File;
  3 import java.io.FileReader;
  4 import java.io.FileNotFoundException;
  5 import java.io.IOException;
  6
  7 public class ReadTextFileExample
  8 {
  9 public static void main(String[] args)
  10 {
  11 File file = new File("test.txt");
  12 StringBuffer contents = new StringBuffer();
  13 BufferedReader reader = null;
  14
  15 try
  16 {
  17 reader = new BufferedReader(new FileReader(file));
  18 String text = null;
  19
  20 // repeat until all lines is read
  21 while ((text = reader.readLine()) != null)
  22 {
  23 contents.append(text)
  24 .append(System.getProperty(
  25 "line.separator"));
  26 } [NextPage]   27 } catch (FileNotFoundException e)
  28 {
  29 e.printStackTrace();
  30 } catch (IOException e)
  31 {
  32 e.printStackTrace();
  33 } finally
  34 {
  35 try
  36 {
  37 if (reader != null)
  38 {
  39 reader.close();
  40 }
  41 } catch (IOException e)
  42 {
  43 e.printStackTrace();
  44 }
  45 }
  46
  47 // show file contents here
  48 System.out.println(contents.toString());
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved