j2sdk1.5提供的文本文件读取-例子

类别:Java 点击:0 评论:0 推荐:

j2sdk1.5提供的文本文件读取,愿与大家分享。
参考文献(来自):SDN - Core Java Technologies Tech Tips

文本文件:hrinfo.txt
        内容:老赵 ,28 ,FEB-01 ,true
                    小竹 ,22 ,DEC-03 ,false
                    阿波 ,21 ,DEC-03 ,false
                    凯子 ,25 ,DEC-03 ,true
例子程序:

   import java.util.Scanner;
   import java.io.File;
   import java.io.FileNotFoundException;

   public class ReadHuman {

     private static void readFile(String fileName) {
       try {
         Scanner scanner = new Scanner(new File(fileName));
         scanner.useDelimiter(System.getProperty("line.separator"));
         while (scanner.hasNext()) {
           parseLine(scanner.next());
         }
         scanner.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       }
     }

     private static void parseLine(String line) {
       Scanner lineScanner = new Scanner(line);
       lineScanner.useDelimiter("\\s*,\\s*");
       //可以修改useDelimiter参数以读取不同分隔符分隔的内容
       String name = lineScanner.next();
       int age = lineScanner.nextInt();
       String idate = lineScanner.next();
       boolean isCertified = lineScanner.nextBoolean();
       System.out.println("姓名:" + name + ",年龄:" + age + ",入司时间:"+idate+",验证标记:" + isCertified );
     }

     public static void main(String[] args) {
       if (args.length != 1) {
         System.err.println("usage: java ReadHuman file location");
         System.exit(0);
       }
       readFile(args[0]);
     }
   }



本文地址:http://com.8s8s.com/it/it11818.htm