192k views
4 votes
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.

User Federicot
by
4.9k points

1 Answer

3 votes

Answer:

See explaination for thr program code.

Step-by-step explanation:

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.util.Scanner;

public class ReadWriteInt

{

public static void main(String args[]) throws IOException

{

Scanner input=new Scanner(System.in);

System.out.println("Enter the name of the input file:");

String inputFile=input.next();

System.out.println("Enter the name of the output file:");

String outputFile=input.next();

File fin=new File(inputFile);

File fout=new File(outputFile);

//print error, if input file does not exist

if(!fin.exists())

{

System.out.println("Error:Input file does not exist");

System.exit(0);

}

//print error, if output file does not exist

if(!fout.exists())

{

System.out.println("Error:output file does not exist");

System.exit(0);

}

//input stream to read

Scanner read=new Scanner(fin);

OutputStream os=new FileOutputStream(fout);

//output stream to write

PrintWriter write=new PrintWriter(os,true);

//read from input file until there are no numbers

while(read.hasNextLine())

{

String num=read.nextLine();

//convert the string into number

int number=Integer.parseInt(num);

//if the number is positive , write it to out put file

if(number>=0)

{

write.println(number);

System.out.println(number);

}

}

System.out.println("Positive numbers are copied successfully");

}

}

Please check attachment for screenshot and output

Write a program that reads a stream of integers from a file and writes only the positive-example-1
Write a program that reads a stream of integers from a file and writes only the positive-example-2
Write a program that reads a stream of integers from a file and writes only the positive-example-3
User AGO
by
4.8k points