简体   繁体   English

如何使用具有完整文件路径的java Scanner类?

[英]How do I use java Scanner class with complete file path?

How do I use it with the complete path? 如何使用完整路径? For example: "/home/user/file.txt"? 例如:“ / 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);
 }
}

if I do this: 如果我这样做:

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);
 }
}

it generates the error: 它产生错误:

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)

If I understand your question then you could use File(String, String) constructor and the "user.home" property to construct that path like 如果我理解您的问题,则可以使用File(String, String)构造函数和“ user.home”属性来构造该路径,例如

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

or (on a DOS based system) if you really prefer 或(在基于DOS的系统上)(如果您确实喜欢)

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

Edit 编辑

A more complete example, and using a try-with-resources statement 一个更完整的示例,并使用try-with-resources语句

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM