java中Scanner類讀取文件或控制台輸入


(1)讀取文件中內容
jdk 5.0新增加了Scanner類,Scanner是一個可以使用正則表達式來解析基本類型和字符串的簡單文本掃描器,Scanner 使用分隔符模式將其輸入分解為標記,默認情況下該分隔符模式與空白匹配(可以使用s.useDelimiter("Pattern || String")指定分隔符)。然后可以使用不同的 next 方法將得到的標記轉換為不同類型的值。
new.txt: java ejb jdk j2me spring jdk flex silverlight jdk j2me j2ee jdk c# asp.net
輸出結果: java ejb j2me spring flex silverlight j2me j2ee c# asp.net

Java代碼
  1. import java.io.*;   
  2. import java.util.Scanner;   
  3.   
  4. public class ScanXan {   
  5.     public static void main(String[] args) throws IOException {   
  6.         Scanner s = null;   
  7.         try {   
  8.             s = new Scanner(new BufferedReader(new FileReader("c:\\new.txt")));   
  9.             //使用字符串jdk作為分隔符   
  10.             s.useDelimiter("jdk");   
  11.             while (s.hasNext()) {   
  12.                 System.out.println(s.next());   
  13.             }   
  14.         } finally {   
  15.             if (s != null) {   
  16.                 s.close();   
  17.             }   
  18.         }   
  19.     }   
  20. }  

(2)讀取控制台輸入

import java.util.Scanner;

public class ScannerTest

{

public static void main(String[] args)

{
  Scanner s = new Scanner(System.in);
  //receive string
  String str = s.next();
 
  //receive integer
  Integer i = s.nextInt();
 
  //receive double
  Double d = s.nextDouble();
 
  System.out.println(str+i+d);
}
}

int x=scanner.nextInt();這表示只接收int類型的數據,如果輸入其他的數據要出問題的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM