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

Java coding. Write a program that reads a stream of integers from a file and wri

ID: 3764235 • Letter: J

Question

Java coding.

Write a program that reads a stream of integers from a file and writes only the positive numbers to a second file. The user should be prompted to enter the names of both the input file and output file in main(), and then main() should attempt to open both files (providing an error if there is an error during this process). The main() method should then call the process() method to read all the integers from the input file and write only the positive integers to the output file. The process() method takes as arguments a Scanner to read from the input and a PrintWriter to write to the output. You can assume that if you are able to successfully open the input file, then there will only be integers in it. You have been supplied JUnit tests for the process() method, as well as the output for several example file contents.

Explanation / Answer

import java.io.Closeable;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Stream {

   public static void main(String[] args) {
       FileReader fr = null;
       FileWriter fw = null;
       PrintWriter printWriter = null;
       Scanner sc = null;
       try {
           sc = new Scanner(System.in);
           System.out.println("Enter first file : ");
           fr = new FileReader(sc.next());
           System.out.println("Enter secound file : ");
           fw = new FileWriter(sc.next());
           printWriter = new PrintWriter(fw);
           int c = fr.read();
           while (c != -1) {
               if (c > 0) {
                   printWriter.print(c);
               }
               c = fr.read();
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           close(fr);
           close(fw);
           close(printWriter);
           close(sc);
       }
   }

   public static void close(Closeable stream) {
       try {
           if (stream != null) {
               stream.close();
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

}

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