基本方法
读取文件内容是非常重要的,实际的业务应用场景几乎都是读取文件的,需要用到FIle、FileInputStream、FileReader、BufferedReader等实现文件读取。
这里总结基本的读取方式,并给出应用实例。
使用Scanner读取数据
java.util.Scanner类,Scanner读取内容,空格作为分隔标记。
Scanner input = new Scanner(new File(filename));是它的具体实现方式。
其中连续读取字符内容可以使用input.next()或input.hasnext(),具体next()的返回值是文件里面的内容,hasnext()的返回值是boolean类型。
public class TestScanner {
public static void main(String[] args) throws IOException {
File file = new File("src/File/ScannerFile");
Scanner sc = new Scanner(file);
while (sc.hasNext()){
String firstName = sc.next();
String secondName = sc.next();
String lastName = sc.next();
System.out.println(firstName + " " + secondName + " " + lastName +" ")