2016-12-15 149 views
0

我可以用java.iojava.util.Scanner讀取文件,但我不知道怎麼只有java.util.Scanner使用讀取文件:的Java讀取文件中使用掃描儀

import java.io.*; 
import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) throws IOException { 
     String filePath = "C:\\IdeaProjects\\test\\src\\input.txt"; 
     Scanner sc = new Scanner(new File(filePath)); 
     int a, b; 
     a = sc.nestInt(); 
     b = sc.nextInt(); 
    } 
} 

有人能幫忙嗎?

+1

[閱讀使用掃描儀類Java中的.txt文件(可能的重複http://stackoverflow.com/questions/13185727/reading-a-txt-文件使用掃描儀類功能於JAVA) –

回答

-1

好吧,如果你使用的是Mac,你輸入這個到終端file.java<input.txt,並輸出到您鍵入此文件:file.java>output.txtoutput.txt是一個不存在的文件,而input.txt是預先存在的文件。

0

如果要讀取的文件,直到結束:

String filePath = "C:\\IdeaProjects\\test\\src\\input.txt"; 
File file = new File(filePath); 

    try { 

     Scanner sc = new Scanner(file); 

     while (sc.hasNextLine()) { 
      int i = sc.nextInt(); 
      System.out.println(i); 
     } 
     sc.close(); 
    } 
    catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

P.S如果每行只有整數,我建議你使用 的Integer.parseInt(sc.readLine());
而不是sc.nextInt();

如果你不能閱讀,請給我文件上下文