введите каталог для Java, чтобы продолжить - PullRequest
0 голосов
/ 08 ноября 2018

У меня проблема здесь. Всякий раз, когда я вводил путь к каталогу, который копировал со своего компьютера для ввода 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 голосов
/ 08 ноября 2018

Ваш кодовый сегмент прекрасно работает на моем ноутбуке. Так что проблема может быть здесь:

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...