Я создал три текстовых файла, inputt.txt, outputt.txt, & errorr.txt. Inputt.txt предназначен для ввода, outputt.txt должен печатать все числа из inputt.txt, которые являются действительными целыми числами, а errorr.txt выводит все ошибки из входного текстового файла. У меня проблемы с итерацией. System.out.println отлично печатает все числа из inputt.txt; однако, когда я пытаюсь напечатать все числа в файле outputt.txt, он печатает только первую строку чисел. Вот мой код:Как перебирать текстовый файл для печати в другой текстовый файл?
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Lab5_Exceptions_Redo extends Exception {
public static void main(String[] args) throws FileNotFoundException {
String file = "inputt.txt";
String file1 = "outputt.txt";
String file2 = "errorr.txt";
PrintWriter errorr = new PrintWriter(file2);
PrintStream ps = new PrintStream(file2);
PrintWriter outputt = new PrintWriter(file1);
Scanner scan = new Scanner(new File(file));
while (scan.hasNext()) {
try {
String number = scan.nextLine();
int num = Integer.parseInt(number);
System.out.println(num);
outputt.println(num);
} catch (InputMismatchException e) {
errorr.println("There was an input mismatch error.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NoSuchElementException e) {
errorr.println("There is no such element.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (UnsupportedOperationException e) {
errorr.println("An unsupported operation occured.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NumberFormatException e) {
errorr.println("Number Format Exception.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
}
errorr.close();
outputt.close();
}
scan.close();
}
}
Вы закрываете 'outputt' в цикле. Переместите его снаружи, чтобы исправить. Голосование закрывается как опечатка. – dasblinkenlight
Я не могу закрыть его снаружи, потому что внутри я объявляю переменные, и я не могу перемещать переменную снаружи, потому что они должны быть в моей инструкции try. – HelpMe