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

Write a program in java that reads a stream of integers from a file and writes o

ID: 3763734 • Letter: W

Question

Write a program in java 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.

Explanation / Answer


import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

/**
* @author Srinivas
*
*/
public class StreamOfInts {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       String inFileName, outFileName;
       Scanner scanner = new Scanner(System.in);

       try {
           System.out.print("Enter the input File name :");
           inFileName = scanner.nextLine();

           System.out.print("Enter the output File name :");
           outFileName = scanner.nextLine();

           File inFile = new File(inFileName + ".txt");
           File outFile = new File(outFileName + ".txt");
           if (inFile.exists() && outFile.exists()) {

           } else {
               outFile.createNewFile();

               Scanner inScanner = new Scanner(inFile);
               PrintWriter printer = new PrintWriter(outFile);

               process(inScanner, printer);
           }

       } catch (Exception e) {
           e.printStackTrace();
       }

   }

   /**
   * @param inScanner
   * @param printer
   */
   public static void process(Scanner inScanner, PrintWriter printer) {
       while (inScanner.hasNextLine()) {

           int value = inScanner.nextInt();
           // System.out.println("value==" + value);
           if (value > 0)
               printer.write(value + " ");
       }
       printer.flush();

   }

}


OUTPUT:

Enter the input File name :infile
Enter the output File name :out

infile.txt
23
43
55
65
-56
-65
78
54
75
23
43
55
65
-56
-65
78
54
75
22
-43

out.txt
23
43
55
65
78
54
75
23
43
55
65
78
54
75
22

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