要将控制台输出到文本文件Java?

问题描述 投票:0回答:3

我正在尝试将程序的输出发送到名为results.txt的文本文件。这是我的尝试

public void writeFile(){
        try{    
            PrintStream r = new PrintStream(new File("Results.txt"));
            PrintStream console = System.out;

            System.setOut(r);
        } catch (FileNotFoundException e){
            System.out.println("Cannot write to file");
        }

但是每次我运行代码并打开文件时,文件都是空白。这是我要输出的内容:

public void characterCount (){
       int l = all.length();
       int c,i;
       char ch,cs;
       for (cs = 'a';cs <='z';cs++){
           c = 0;
           for (i = 0; i < l; i++){
               ch = all.charAt(i);
               if (cs == ch){
                   c++;
               }

           }
           if (c!=0){
//THIS LINE IS WHAT I'M TRYING TO PRINT
                System.out.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
           }
       }
    }

我在哪里出错,因为它一直在创建文件但不写入文件?(顺便说一句,我确实有一种主要方法)

java filereader filewriter file-writing console-output
3个回答
1
投票

用途:

PrintWriter writer = new PrintWriter("Results.txt");

writer.print("something something");

不要忘记添加:

writer.close();

完成后!


1
投票

正如您所发现的,System.out IS-A PrintStream,您可以创建一个PrintStream,并向其传递一个File以使其写入该文件。这就是多态的美丽---您的代码写到PrintStream上,与它的类型无关:控制台,文件,甚至网络连接或压缩的网络文件。

因此,不要搞乱System.setOut(通常是一个坏主意,因为它可能具有意想不到的副作用;仅在绝对必须(例如,在某些测试中)时才这样做),只需通过您选择的PrintStream到您的代码:

public void characterCount (PrintStream writeTo) {
    // (your code goes here)
    writeTo.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
    // (rest of your code)
}

然后您可以根据需要调用方法:

public static void main(String[] args) throws FileNotFoundException {
    new YourClass().characterCount(System.out);
    new YourClass().characterCount(new PrintStream(new File("Results.txt")));
}

((请注意,我声明main可能会抛出FileNotFoundException,因为new File("...")会抛出该错误。当发生这种情况时,程序将退出并显示一条错误消息和堆栈跟踪信息。您也可以像以前那样处理它writeFile中的之前。)


0
投票

JAVADOC:“一个PrintStream向另一个输出流添加了功能,即能够方便地打印各种数据值的表示形式。”

PrintStream可用于写入OutputStream,而不是直接写入文件。因此,您可以使用PrintStream写入FileOutputStream,然后使用它来写入文件。

但是,如果您只想简单地写入文件,则可以使用Cans答案!

© www.soinside.com 2019 - 2024. All rights reserved.