如何将java Scanner类与完整文件路径一起使用?

时间:2015-01-13 15:48:26

标签: java

如何在完整路径中使用它?例如:" /home/user/file.txt"?

public class ScannerSample {

  public static void main(String[] args) throws FileNotFoundException {
  //Z means: "The end of the input but for the final terminator, if any"
     String output = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
     System.out.println("" + output);
 }
}

如果我这样做:

public class ScannerSample {

  public static void main(String[] args) throws FileNotFoundException {
  //Z means: "The end of the input but for the final terminator, if any"
     String output = new Scanner(new File("/home/user/file.txt")).useDelimiter("\\Z").next();
     System.out.println("" + output);
 }
}

它会生成错误:

java.io.FileNotFoundException: \home\user\file.txt (The system cannot find the path specified)
java.io.FileInputStream.open(Native Method)
java.io.FileInputStream.<init>(Unknown Source)
java.util.Scanner.<init>(Unknown Source)
util.CompareDevices.doPost(CompareDevices.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

1 个答案:

答案 0 :(得分:4)

如果我理解了您的问题,那么您可以使用File(String, String)构造函数和&#34; user.home&#34;用于构造该路径的属性,如

new File(System.getProperty("user.home"), "file.txt")

或(在基于DOS的系统上)如果你真的喜欢

new File("c:/home/user/file.txt")

修改

更完整的示例,并使用try-with-resources statement

File f = new File(System.getProperty("user.home"), "file.txt");
try (Scanner scanner = new Scanner(f)) {
    scanner.useDelimiter("\\Z");
    String output = scanner.next();
    System.out.println(output);
} catch (Exception e) {
    e.printStackTrace();
}