简体   繁体   English

如何将终端输出(和输入)复制到Java中的文件

[英]How to copy the terminal output (and input) to a file in java

I want to save all the text on the terminal as a output on a text file. 我想将终端上的所有文本保存为文本文件的输出。 For the output there can be a function to be used instead of System.out.println() 对于输出,可以使用一个函数代替System.out.println()

    class OutSave
{
    String output;
    public static void main()
    {
        output="";
        print("Print this");
        print("And save this");
    }
    public static print(String p)
    {
        output=output+"\n"+p;
        System.out.println(p);
    }
}

Something like this but I cannot figure this out for the inputs supplied by the user. 这样的事情,但我无法为用户提供的输入弄清楚。

Thanks in Advance 提前致谢

The usual way of doing this doesn't require doing anything inside your Java program, and works for any program, regardless of the language it was originally written in. 这样做的通常方法不需要在Java程序内执行任何操作,并且对任何程序都有效,而不论它最初是用什么语言编写的。

From a command line, in most shells (bash, C shell, MS-DOS, etc.), run: 在大多数外壳程序(bash,C shell,MS-DOS等)中,从命令行运行:

$program > outfile.txt

Where $program is the name of the executable. 其中$program是可执行文件的名称。

This is commonly known as redirection . 这通常称为重定向

Here is a simple example of how to write a log file of what you are printing. 这是一个简单的示例,说明如何写入要打印的日志文件。

class OutSave
{

    File output = new File("output.txt");

    public static void main()
    {
        print("Print this");
        print("And save this");
    }

    public static print(String str)
    {
        System.out.println(str);
        writeToFile(output, str);
    }

    public void writeToFile(File file, String str) {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write(str);
        bw.close();
    }
}

Edit: Log user input (ints) 编辑:记录用户输入(整数)

    Boolean running = true;
    System.out.println("Enter a Number: ");

    while (true) {
        while (!sc.hasNextInt()) {
            System.out.println("Try again, Enter a Number: "); //invalid entry
            sc.nextLine();
        }
        WriteToFile(output, Integer.toString(sc.nextInt()));
    }

You could call this code from a method then change the running boolean to exit the loop when you are done as this will hang your program in the input loop if you do not exit. 您可以从方法中调用此代码,然后在完成后更改正在运行的布尔值以退出循环,因为如果不退出,这会将程序挂在输入循环中。 Might be a good idea to thread this too. 也可以将其穿线。

您可以使用File writer检查链接: http : //java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM