Как показать/записать результат в файл журнала?

Я должен записать/показать ввод моего результата (калькулятора) в файл журнала... например: results.txt Но если я сделаю более 1 вычисления... только последний будет напечатан в results.txt.

public class Calculator {
    public static void main(String[] args) throws FileNotFoundException {
        String filename = "results.txt";
        //PrintWriter output = new PrintWriter(filename);
        int number1;
        int number2;
        char mathchoice;
        int result;
        char userchoice;
        do {
            PrintWriter output = new PrintWriter(filename);

            Scanner choice = new Scanner(System.in);
            System.out.println("Enter first number...");
            number1 = choice.nextInt();
            System.out.println("Math choice...");
            mathchoice = choice.next().charAt(0);
            System.out.println("Enter second number...");
            number2 = choice.nextInt();

            if (mathchoice == '+') {
                result = number1 + number2;
                System.out.println("Result is: " + result);
                output.print("Result is: " + result);
            } else if (mathchoice == '-') {
                result = number1 - number2;
                System.out.println("Result is: " + result);
                output.print("Result is: " + result);
            } else if (mathchoice == '*') {
                result = number1 * number2;
                output.print("Result is: " + result);
                System.out.println("Result is: " + result);
            } else if (mathchoice == '/') {
                if (number2 == 0) {
                    throw new java.lang.ArithmeticException("Devided by zero not aloud");
                } else {
                    result = number1 / number2;
                    output.print("Result is: " + result);
                    System.out.println("Result is: " + result);

                }

            } else if (mathchoice == '%') {
                result = number1 % number2;
                output.print("Result is: " + result);
                System.out.println("Result is: " + result);
            } else if (mathchoice == '^') {
                result = (int) Math.pow(number1, number2);
                output.print("Result is: " + result);
                System.out.println("Result is: " + result);
            } else {
                System.out.println("Wrong choice");

            }
            output.close();
            System.out.println("Again?");
            userchoice = choice.next().charAt(0);

        }while (userchoice == 'j');
    }
    
}

Я добавил output.close() в конце lus. Но я получаю только последний расчет.


person Pedro Costa    schedule 04.10.2020    source источник


Ответы (2)


Вы можете создать файл и писать в него напрямую, см. классы java.io, такие как OutputStream, FileWriter и т. д. В основном вам нужно создать ссылку на файл и использовать метод записи для записи в него.

// on Windows use "c:\temp\my-file.log"
FileOutputStream fos = new FileOutputStream("/tmp/my-file.log");
fos.write("My log message".getBytes());

Но по возможности не изобретайте велосипед и используйте LOG4J для записи своих логов. LOG4J — широко используемая библиотека, которая значительно упрощает работу с журналами.

А для управления зависимостями вашего проекта используйте Maven. Создайте проект maven и добавьте зависимости в POM.XML, это сильно упростит вам жизнь.

person ETN    schedule 04.10.2020

Если вы хотите получить точно такой же вывод, как напечатанный в консоли, то есть System.out + System.in, один из способов сделать это — создать пользовательский InputStreamReader для передачи сканеру и пользовательский PrintStream для установки System. как. Эти пользовательские реализации могут затем записывать в файл всякий раз, когда они читают/записывают данные.

Вот пример:

import java.io.*;
import java.nio.file.Paths;
import java.util.Scanner;

public class ScannerTest {

    static boolean alive = true;

    public static void main(String[] args){

        int number1;
        int number2;
        char mathchoice;
        int result;
        char userchoice;

        final File file = Paths.get("result.txt").toFile();

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            file.createNewFile();
            System.setOut(new PrintStreamFileForwarder(System.out, fileOutputStream));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Scanner choice = new Scanner(new InputStreamFileForwarder(System.in, fileOutputStream));

        do {

            System.out.println("Enter first number...");
            number1 = choice.nextInt();
            System.out.println("Math choice...");
            mathchoice = choice.next().charAt(0);
            System.out.println("Enter second number...");
            number2 = choice.nextInt();

            if (mathchoice == '+') {
                result = number1 + number2;
                System.out.println("Result is: " + result);
            } else if (mathchoice == '-') {
                result = number1 - number2;
                System.out.println("Result is: " + result);
            } else if (mathchoice == '*') {
                result = number1 * number2;
                System.out.println("Result is: " + result);
            } else if (mathchoice == '/') {
                if (number2 == 0) {
                    throw new java.lang.ArithmeticException("Devided by zero not aloud");
                } else {
                    result = number1 / number2;
                    System.out.println("Result is: " + result);
                }

            } else if (mathchoice == '%') {
                result = number1 % number2;
                System.out.println("Result is: " + result);
            } else if (mathchoice == '^') {
                result = (int) Math.pow(number1, number2);
                System.out.println("Result is: " + result);
            } else {
                System.out.println("Wrong choice");

            }
            System.out.println("Again?");
            userchoice = choice.next().charAt(0);

        } while (userchoice == 'j');
        alive = false;
    }

    public static class InputStreamFileForwarder extends InputStreamReader {

        private final FileOutputStream fileOutputStream;

        public InputStreamFileForwarder(InputStream console, FileOutputStream fileOutputStream) {
            super(console);
            this.fileOutputStream = fileOutputStream;
        }

        @Override
        public int read(char[] cbuf, int offset, int length) throws IOException {
            int read = super.read(cbuf, offset, length);
            if(read > 0) {
                char[] allRead = new char[read];
                System.arraycopy(cbuf, offset, allRead, 0, read);
                fileOutputStream.write(new String(allRead).getBytes());
            }
            return read;
        }
    }

    public static class PrintStreamFileForwarder extends PrintStream {

        private final FileOutputStream fileOutputStream;

        public PrintStreamFileForwarder(PrintStream console, FileOutputStream fileOutputStream) {
            super(console);
            this.fileOutputStream = fileOutputStream;
        }

        @Override
        public void write(byte[] buf, int off, int len) {
            super.write(buf, off, len);
            try {
                fileOutputStream.write(buf, off, len);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
person Stan van der Bend    schedule 04.10.2020
comment
Стэн, есть ли более простой способ сделать это? - person Pedro Costa; 04.10.2020
comment
@PedroCosta Я не знаю более простого/простого способа сделать это. Код довольно прост, правда? U по существу оборачивает класс вокруг потока ввода и потока печати. Я просмотрел API класса Scanner и не увидел готовых решений для вашей проблемы :( - person Stan van der Bend; 04.10.2020