java - 将输入保存到文件

标签 java file io command

我正在构建一个命令 shell,在这个命令 shell 中我想保存我写入文件的每个命令。

我读的命令是这样的:

    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    commandLine = console.readLine();

我像这样写入文件:

    public static void fileWriter(String e){
    try{
        BufferedWriter bw = new BufferedWriter(new FileWriter("errorLog.txt"));
            bw.write(e);
            bw.flush();
            bw.close();
    }
    catch(IOException ex){
        System.out.println(ex);
    }        
}

问题是,每个命令都会覆盖最后一个命令,因此我无法保存在命令 shell session 期间写入的每个命令。我需要的是我编写的所有命令的列表。

我已经用谷歌搜索了大约两个小时,但找不到任何东西。请帮忙。

最佳答案

使用

BufferedWriter bw = new BufferedWriter(new FileWriter("errorLog.txt",true));

true 告诉 FileWriter 追加数据而不是覆盖。请参阅文档。

public FileWriter(String fileName,boolean append) throws IOException

Constructs a FileWriter object given a file name with a boolean 
indicating whether or not to append the data written. 

关于java - 将输入保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16286723/

相关文章:

c - 将嵌入式可执行二进制文件从 C 程序写入文件

Haskell Lazy ByteString + 读/写进度函数

java - 为什么Outputstream = new BufferedOutputStream没有缓冲?

java - 列出目录中的所有文件夹,即使添加新文件也不更改顺序

delphi - 防止 TWebBrowser 接受删除的文件

c - 将 void * 缓冲区用作 char * 以外的任何缓冲区是否合法?

java - 在 Java 中计算三角表达式

java - 从给定整数数组中查找最接近中间范围的数字的方法

java - 更改我的 java 绘图程序中的颜色

java - 使用计时器对 Java 线条图进行动画处理