title: To print console output to text file Java?
body: <p>I'm trying to send the output of my program to a text file called results.txt . Here's my attempt</p>
  
  <pre><code>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");
          }
  </code></pre>
  
  <p>But everytime I run the code and open the file the file is blank. This is what i want to output:</p>
  
  <pre><code>public void characterCount (){
         int l = all.length();
         int c,i;
         char ch,cs;
         for (cs = 'a';cs &lt;='z';cs++){
             c = 0;
             for (i = 0; i &lt; 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 --&gt; "+" "+c+" "+ "times");
             }
         }
      }
  </code></pre>
  
  <p>Where am I going wrong that it keeps creating the file but not writing to it?
  (Btw i do have a main method)</p>