Java Scanner类
时间:2020-02-23 14:37:24 来源:igfitidea点击:
Java 1.5中引入了Java的Scanner类(java.util.Scanner
),它是一种简单的文本扫描程序,可以使用正则表达式解析原始类型和字符串。
Java Scanner类
Java Scanner类可用于使用任何正则表达式定界符将输入分解为令牌,这对于解析文件也非常有用。
扫描程序类可用于将文件数据读取为原始数据。
它还扩展了String split()方法以将令牌作为String,int,long,Integer和其他包装器类返回。
Java Scanner示例
其中我使用Scanner逐行读取文件,解析CSV文件以轻松创建java对象并从用户输入中读取。
JavaFileScanner.java
package com.theitroad.files; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; public class JavaFileScanner { public static void main(String[] args) throws IOException { /** * My Name is hyman * My website is theitroad.local * Phone : 1234567890 */ String fileName = "/Users/hyman/source.txt"; Path path = Paths.get(fileName); Scanner scanner = new Scanner(path); //read file line by line scanner.useDelimiter(System.getProperty("line.separator")); while(scanner.hasNext()){ System.out.println("Lines: "+scanner.next()); } scanner.close(); //read CSV Files and parse it to object array /** * hyman,28,Male * Lisa,30,Female * Mike,25,Male */ scanner = new Scanner(Paths.get("/Users/hyman/data.csv")); scanner.useDelimiter(System.getProperty("line.separator")); while(scanner.hasNext()){ //parse line to get Emp Object Employee emp = parseCSVLine(scanner.next()); System.out.println(emp.toString()); } scanner.close(); //read from system input System.out.println("Read from system input:"); scanner = new Scanner(System.in); System.out.println("Input first word: "+scanner.next()); } private static Employee parseCSVLine(String line) { Scanner scanner = new Scanner(line); scanner.useDelimiter("\s*,\s*"); String name = scanner.next(); int age = scanner.nextInt(); String gender = scanner.next(); JavaFileScanner jfs = new JavaFileScanner(); return jfs.new Employee(name, age, gender); } public class Employee{ private String name; private int age; private String gender; public Employee(String n, int a, String gen){ this.name = n; this.age = a; this.gender = gen; } @Override public String toString(){ return "Name="+this.name+"::Age="+this.age+"::Gender="+this.gender; } } }
上面程序的输出是:
Lines: My Name is hyman Lines: My website is theitroad.local Lines: Phone : 1234567890 Name=hyman::Age=28::Gender=Male Name=Lisa::Age=30::Gender=Female Name=Mike::Age=25::Gender=Male Read from system input: hyman Kumar Input first word: hyman
我们可以使用java Scanner类将输入解析为特定的数据类型标记。