程序无法从.txt文件中读取

时间:2015-11-17 17:32:55

标签: java

我正在尝试从名为input的txt文件中读取三个变量 input.txt包含12 33.44和Peter 当我运行程序时,这些变量不会输出

package lab9;
import java.util.Scanner;              // Needed to use Scanner for input
import java.io.File;                   // Needed to use File
import java.io.FileNotFoundException;  // Needed for file operation

public class FileScanner 
{ 
   public static void main(String[] args) 
  // Needed for file operation 
         throws FileNotFoundException 
   {  

// Declare the int variable
       int a=0;
 //Declare the floating point number
       double b=0;
 //Declare the string variable
       String s=null;
 //Declare a variable to hold the sum
       double sum =0;
// Create a file object that takes "input.txt" as input
       File oInput= new File("input.txt") ;
// Setup a Scanner to read from the text file that you created
       Scanner gilz=new Scanner(oInput);

// use nextInt() to read the integer
       while (gilz.hasNextInt())
       {
         a = gilz.nextInt();
       }
         System.out.println ("the integer read is " + a);

// use nextDouble() to read double
     while(gilz.hasNextDouble())
     {
         b = gilz.nextDouble();
     }
         System.out.println ("the floating point number read is "+ b);

// use next() to read String
       while(gilz.hasNextLine())
       {
       s = gilz.nextLine();
       }
         System.out.println ("the string read is "+ s);
       while((gilz.hasNextDouble())&&(gilz.hasNextInt()))
       {
           sum = a + b;
       }
           System.out.println("HI! "+s +", the sum of "+a+"and "+b+" is "+sum);
    }
}

当我尝试运行程序时,我没有输出,屏幕上没有打印变量 如何使用.nextInt()或.next()方法让我的扫描仪从txt文件中读取?

1 个答案:

答案 0 :(得分:-2)

使用您将阅读的文件的完整路径。 我正在使用FileReader和BufferedReader的示例,您需要使用新的File("c:\\input.txt)执行相同的操作。

请看下面的示例:

public static void main(String[] args) {

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("C:\\input.txt"));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
相关问题