Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I\'m writing a java program that parses some info from a file. I was able

ID: 3771611 • Letter: H

Question

Hello, I'm writing a java program that parses some info from a file. I was able to print and format all the information to the terminal just fine. Now I need to print that info into a file. The problem is I have diferent methods/classes all over the place that could all print to system.out.printf(), but when I declare a "BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));" I get all kinds of out of scope errors when I try to switch out my old System.out with my new buffered writer. I'm new to java, is there a syntax/place to declare a bufferedwriter so that it is global and everything can use it? My goal is to switch out all my System.out.printf() commands with writer.write() and just have it print the info to my file and not the terminal. Thank you

Explanation / Answer

Define new class writer and provide a static method in that to write to file.

Replace your system.out.print statemetns with

Writer.write()

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Writer {

   static BufferedWriter writer = null;
  
   //if you writing all data into same file from differnt classes and methods
   public static void write(String str) throws IOException {
       //create the file its null only
       if(writer == null)
           writer = new BufferedWriter(new FileWriter("filename"));
      
       writer.write(str);
   }
  
  
   //if you write into different files
   public static void write(String filename, String str) throws IOException {
       //create the file its null only
       writer = new BufferedWriter(new FileWriter(filename));
      
       writer.write(str);
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote