如何在日志文件中显示/写入结果?

huangapple go评论66阅读模式
英文:

How to show/write result in log file?

问题

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

            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.println("Result is: " + result); // Use println to write to a new line
            } else if (mathchoice == '-') {
                result = number1 - number2;
                System.out.println("Result is: " + result);
                output.println("Result is: " + result);
            } else if (mathchoice == '*') {
                result = number1 * number2;
                output.println("Result is: " + result);
                System.out.println("Result is: " + result);
            } else if (mathchoice == '/') {
                if (number2 == 0) {
                    throw new java.lang.ArithmeticException("Divided by zero not allowed");
                } else {
                    result = number1 / number2;
                    output.println("Result is: " + result);
                    System.out.println("Result is: " + result);
                }
            } else if (mathchoice == '%') {
                result = number1 % number2;
                output.println("Result is: " + result);
                System.out.println("Result is: " + result);
            } else if (mathchoice == '^') {
                result = (int) Math.pow(number1, number2);
                output.println("Result is: " + result);
                System.out.println("Result is: " + result);
            } else {
                System.out.println("Wrong choice");
            }

            output.close(); // Close the PrintWriter within the loop

            System.out.println("Again?");
            userchoice = choice.next().charAt(0);
        } while (userchoice == 'j');
    }
}
英文:

I am supposed to write/show input of my "result"(calculator) to a log file... for example: results.txt
But If I do more then 1 calculation... only the last one gets printed in 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');
}
}

I added the output.close(), at the end of the lus. But I only get the last calculation.

答案1

得分: 1

你可以创建一个文件并直接写入内容,查看"java.io"类,如OutputStream、FileWriter等。
基本上你需要创建一个文件的引用,并使用"write"方法将内容写入。

// 在Windows下使用"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中添加依赖,这将极大地简化你的工作。

英文:

You can create a file and write directly to it, see the "java.io" classes, such as OutputStream, FileWriter and etc.
You basically need to create a reference to the file and use the "write" method to write to it.

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

But if possible, do not reinvent the wheel and use LOG4J to record your logs.
LOG4J is a widely used library and it makes logging work much easier.

And to manage your project's dependencies, use Maven.
Create a maven project and add the dependencies in POM.XML, it will greatly simplify your life.

答案2

得分: 1

如果你想要获得与控制台中打印的完全相同的输出即 System.out + System.in一种方法是创建一个自定义的 InputStreamReader 并提供给 Scanner 使用以及一个自定义的 PrintStream 来设置 System.out这些自定义实现可以在读取/写入数据时将其写入文件中

以下是一个示例

```java
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();
            }
        }
    }
}
英文:

If you want to get the exact same output as printed in the console, so System.out + System.in, one way to go about this is by creating a custom InputStreamReader to give to the Scanner, and a custom PrintStream to set System.out as. These custom implementations can then write to the file whenever they read/write data.

Here is an example:

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();
}
}
}
}

huangapple
  • 本文由 发表于 2020年10月4日 22:49:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64196085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定