2014-02-12 205 views
-4

好的,我使用这段代码从文件中读取,但它返回文件名。从java中读取文件

public void read(String file){ 
    Scanner sc = new Scanner(file); 
    System.out.println(sc.nextInt()); 
    sc.close(); 
} 

我想知道如何在读取文件之前检查文件是否不存在。

+3

阅读类使用的javadoc _before_使用它们。 –

+1

使用带有'FileNotFoundException'的try/catch块。 –

+1

如果你想读取文件的内容,使用'new Scanner(new File(“pathToFile”))''。如果你使用'新的扫描仪(“一些字符串”)它将只读取传递的字符串的内容。 – Pshemo

回答

0
File file = new File("path of file here..."); 

BufferedReader in = new BufferedReader(new FileReader(file)); 
String line; 
while((line=in.readLine())!=null){ 
System.out.println(line); 

} 
+0

谢谢,先生 –

+1

@angeldarkland如果这是正确的答案,[接受它](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 –

0

尝试,这可能是有帮助的:

FileInputStream stream = new FileInputStream("src/transactions.txt"); 
fileIn = new Scanner(stream); 
0

的扫描仪,可以采取多种输入字符串/流/等。我会认真考虑按照Sotirios Delimanolis的建议,尽早阅读javadoc。

public void read (String filename) { 
    try { 
     Scanner sc = new Scanner(new File(filename));  
     System.out.println(sc.nextInt()); 
     sc.close(); 
    } catch (FileNotFoundException) { 
     //handle your error here 
    } 
} 
0

使用file.exists()方法检查文件是否有效。

0

代码段的帮助:

BufferedReader br = new BufferedReader(new FileReader("filepath")); 
     try { 
      StringBuilder sb = new StringBuilder(); 
      String line = br.readLine(); 

      while (line != null) { 
       sb.append(line); 
       sb.append(System.getProperty("line.separator")); 
       line = br.readLine(); 
      } 
      everything = sb.toString(); 
      System.out.println(everything); 
     } finally { 
      br.close(); 
     }