Write a JAVA program that reads a stream of integers from a file and writes only
ID: 3764871 • Letter: W
Question
Write a JAVA 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.
Explanation / Answer
import java.io.*;
import java.util.*;
class main{
public static void main(String[] args){
BufferedReader br = null;
try{
String line;
Scanner sc = new Scanner(System.in);
System.out.print("Enter input file name : ");
String input_file_name = sc.nextLine();
br = new BufferedReader(new FileReader(input_file_name));
System.out.print("Enter output file name : ");
String output_file_name = sc.nextLine();
File file = new File(output_file_name);
// if file doesnt exists, then create it
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
int i = Integer.parseInt(line);
if (i > 0)
bw.write(i + ' ');
}
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.