输入目录到Java进行

时间:2018-11-08 01:28:20

标签: java filereader

我在这里有问题。每当我输入要从计算机复制的目录路径以将txt文件输入到程序时,它总是表示找不到该文件。我的代码有问题吗?

System.out.println("insert directory file = ");
FileReader file = null;
try {
    file = new FileReader(input.next());                
    BufferedReader readfile = new BufferedReader(file);              
    StringBuffer sb = new StringBuffer();
    try {
        while ((text = readfile.readLine()) != null) {
            sb.append(text);
            sb.append("\n");
        }
        readfile.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    text = sb.toString();
    //System.out.println(text);
    System.out.println("Data entered");
    System.out.println("Data length = "+text.length()+"\n");
} catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
    System.out.println("File not found. Pease insert the proper file directory.\n");
}

1 个答案:

答案 0 :(得分:0)

您的代码段在我的笔记本电脑上运行正常。所以问题可能在这里:

file = new FileReader(input.next());

在读取路径之前,是否将扫描仪用于其他输入?尝试将其更改为

String path = input.next();
file = new FileReader(path);

并在发生错误时打印路径,以查看实际传递给FileReader的内容。

catch (FileNotFoundException e1) {
    System.out.println("File not found. Pease insert the proper file directory.\n");
    System.out.println("Your input path: " + path);
}

这是我机器上的工作代码:

public static void main(String[] args) {
  String path = null;
  try (Scanner input = new Scanner(System.in)) {
    System.out.print("Input your option = ");
    int option = input.nextInt();
    switch (option) {
      case 1:
        System.out.println("insert directory file = ");
        String text = "";
        path = input.next();
        FileReader fileReader = new FileReader(path);
        BufferedReader readfile = new BufferedReader(fileReader);
        StringBuffer sb = new StringBuffer();
        try {
          while ((text = readfile.readLine()) != null) {
            sb.append(text);
            sb.append("\n");
          }
          readfile.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        text = sb.toString();
        System.out.println("Data entered");
        System.out.println("Data length = " + text.length() + "\n");
        break;
      default:
        System.out.println("There is nothing to do.");
        break;
    }
  } catch (FileNotFoundException e1) {
    System.out.println("File not found. Pease insert the proper file directory.");
    System.out.println("Your input path is : " + path);
  }
}

enter image description here