2013-05-31 58 views
0

我的代码不是从文件读取行。但我不知道为什么。初级Java,任何输入都很有帮助。java故障从文件读取行

谢谢。

public class ReverseWords { 

public static void main(String [] args){ 
    Scanner in = new Scanner(System.in); 
    System.out.print("Enter File Name: "); 
    String fileName = in.nextLine(); 
    File f = new File(fileName); 
    try { 
     Scanner input = new Scanner(f); 
        int n = input.nextInt(); 
     String line = input.nextLine(); 
      System.out.println(line); 
      String [] words = line.split(" "); 

      for(int i=0; i<words.length; i++){ 
       System.out.println(words[i]); 

      } 


      } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

}  
+2

请问你的文件的内容样子?我怀疑问题是nextInt()不是直到最后一行读取行(它留下新的行标记),所以第一个'nextLine()'返回空字符串(因为它是Scanner在新行之前唯一可以找到的东西标记),第二个nextLine()将读取正确的数据。 – Pshemo

+1

我认为问题在于阅读int。尝试删除行'int in = input.nextInt();' – 2013-05-31 17:19:55

+1

您能显示文件的内容吗? –

回答

1

没有文件内容我只能猜测。

nextInt()不会更改Scanner中的行计数器,因此nextLine()调用将返回当前行的其余行。 这可能不是你想要的,这是为什么没有行被读取的原因。

为了避免这种情况,你可以明确后做一个额外的nextLine()呼叫改变行计数器您nextInt()

int n = input.nextInt(); 
input.nextLine(); 
String line = input.nextLine(); 

Scanner.nextLine API文档:

此方法返回当前行的其余部分,最后不包括任何行 分隔符。

0

我假设你有filenotfound异常。

你必须指定绝对路径作为输入。

drive:/sample/input.txt 

首先尝试从直接

Scanner sc = new Scanner(new File("drive:/dir/file")); 

读取源文件,也可以地方你的项目中存在的文件。 [该文件夹被命名为项目名称] 在这种情况下,您可以只需指定“file.extesion”作为从该文件读取的输入。

但是,如果该文件存在:然后检查是否有输入读取

读取整个文件或进一步行,你应该把在(可以用新的文件(FILENAME.EXT).exists()检查)环(你实际上只读一行)

while(sc.hasnextLine()) 
{ 
line=sc.nextLine() //check it first and then process 
//process this line for words 

}

+0

以及它的读取文件的第一行,hwich是一个int,而不是第二行 – XcutionX

+0

我希望现在能够运作? – Dineshkumar

+0

...仍然没有工作..不知道为什么它没有正确读取文件... – XcutionX