2016-12-15 66 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();

如果你不能阅读,请给我文件上下文