2017-02-08 3 views
-1

Назначение является чтение Строка строки и три ИНТ строки из текстового файла, который буквально выглядит следующим образом (без пробелов между строк):Чтение из текстового файла с использованием класса TextIO?

Алекс Миллер

Для этого мне нужно прочитать файл, используя класс TextIO, который имеет кучу статического метода (подпрограммы, как книга относится к ним) для ввода/вывода. Вот только фрагмент кода от TextIO класс для метода readLine(), который я пытаюсь использовать, безуспешно.

 /** 
    * Opens a file with a specified name for input. If the file name is null, this has 
    * the same effect as calling readStandardInput(); that is, input will be read from standard 
    * input. If an 
    * error occurs while trying to open the file, an exception of type IllegalArgumentException 
    * is thrown, and the input source is not changed. If the file is opened 
    * successfully, then after this method is called, all of the input routines will read 
    * from the file, instead of from standard input. 
    */ 
    public static void readFile(String fileName) { 
     if (fileName == null) // Go back to reading standard input 
     readStandardInput(); 
     else { 
     BufferedReader newin; 
     try { 
      newin = new BufferedReader(new FileReader(fileName)); 
     } 
     catch (Exception e) { 
      throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n" 
          + "(Error :" + e + ")"); 
     } 
     if (! readingStandardInput) { // close current input stream 
      try { 
       in.close(); 
      } 
      catch (Exception e) { 
      } 
     } 
     emptyBuffer(); // Added November 2007 
     in = newin; 
     readingStandardInput = false; 
     inputErrorCount = 0; 
     inputFileName = fileName; 
     } 
    } 

Это то, что я пытаюсь сделать:

public class ReadingFromFile { 

    public static void main(String[] args) { 
     String name;  // The student's name, from the first line of the file. 
      int exam1, exam2, exam3;  // The student's grades on the three exams. 
      double average; // The average of the three exam grades. 

      TextIO.readFile("testdata.txt"); // Read from the file. 

      name = TextIO.getln(); // Reads the entire first line of the file. 
      exam1 = TextIO.getlnInt(); 
      exam2 = TextIO.getlnInt(); 
      exam3 = TextIO.getlnInt(); 

      average = (exam1 + exam2 + exam3)/3.0; 

      System.out.printf("The average grade for %s was %1.1f", name, average); 
      System.out.println(); 
    } 
} 

Но я получаю сообщение:

Исключение в нити "основной" java.lang.IllegalArgumentException: Не удалось открыть файл «testdata.txt» для ввода. (Ошибка: java.io.FileNotFoundException: testdata.txt (система не может найти указанный путь)) на TextIO.readFile (TextIO.java:133) на ReadingFromFile.main (ReadingFromFile.java:9)

Это TextIO.java:133 фактически

throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n" 
         + "(Error :" + e + ")"); 

Я также попытался ввести имя папки путь для datatest.text как это:

TextIO.readFile("src/default package/testdata.txt"); 

Но опять-таки я получаю такое же исключение.

Как читать из файла с помощью этого класса?

+0

Путем указания правильного пути. Я сомневаюсь, что вы запускаете свою программу в 'src/default package /', поэтому использование только 'testdata.txt' обречено на провал. Если вы введете полный путь к файлу, он должен по крайней мере дать вам другую ошибку. – Kayaman

+1

также, возможно, попробуйте ввести путь, такой формат: «C: \\ test \\ test \\ test \\ test.txt» – XtremeBaumer

+0

У вас на самом деле есть пакет под названием «пакет по умолчанию»? Или вы просто думаете, что у вас есть такой пакет, потому что ваша IDE говорит, что это курсивный шрифт? – Tom

ответ

0

поэтому я тестировал фрагмент кода, как это:

public static void main(String[] args) { 
    String name;  // The student's name, from the first line of the file. 
    int exam1, exam2, exam3;  // The student's grades on the three exams. 
    double average; // The average of the three exam grades. 

    TextIO.readFile("C:/Users/username/Desktop/test.txt"); // Read from the file. 

    name = TextIO.getln(); // Reads the entire first line of the file. 
    exam1 = TextIO.getlnInt(); 
    exam2 = TextIO.getlnInt(); 
    exam3 = TextIO.getlnInt(); 

    average = (exam1 + exam2 + exam3)/3.0; 

    System.out.printf("The average grade for %s was %1.1f", name, average); 
    System.out.println(); 
} 

текстовый файл, глядя, как этот

asd 
2 
3 
4 

выход был: The average grade for asd was 3.0

вы скопировали то время как TextIO класс?

Смежные вопросы