SlideShare a Scribd company logo
1 of 7
Download to read offline
Need help with this java code. fill in lines where needed. Also, not sure how to make the text
files and load them into program. Thanks!!
Create a package named "reading_with_exceptions". Write a class named:
Reading_With_Exceptions with the following method:
void process(String inputFilename)
Your program will encounter errors, and we want you to gracefully handle them in such a way
that you print out informative information and continue executing.
Your process routine will try to open a file with the name of inputFilename for input. If there is
any problem (i.e. the file doesn't exist), then you should catch the exception, give an appropriate
error and then return. Otherwise, your program reads the file for instructions.
Your process routine will read the first line of the file looking for an outputFilename String
followed by an integer. i.e.:
outputFilename number_to_read
Your program will want to write output to a file having the name outputFilename. Your program
will try to read from "inputFilename" the number of integers found in "number_to_read".
Your process method will copy the integers read from inputFilename and write them to your
output file(i.e. outputFilename). There should contain 10 numbers per line of output in your
output file.
If you encounter bad input, your program should not die with an exception. For example:
If the count of the numbers to be read is bad or < 0 you will print out a complaint message and
then read as many integers as you find.
If any of the other numbers are bad, print a complaint message and skip over the data
If you don't have enough input numbers, complain but do not abort
After you have processed inputFilename, I would like your program to then close the output file
and tell the user that the file is created. Then Open up the output file and copy it to the Screen.
For example, if inputFilename contained:
We would expect the output of your program to be (Note that after 23 numbers we stop printing
numbers):
The main program will access the command line to obtain the list of filenames to call your
process routine with.
For those of you who benefit from a Template, your program might look like:
To prove that your program works, I want you to run your program with the following command
line parameters:
file1.txt non-existent-file file2.txt file3.txt
Where non-existent-file does not exist.
file1.txt contains:
file2.txt contains:
file3.txt contains:
Solution
// Reading_With_Exceptions.java
import java.io.File; // required imports for the code
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class Reading_With_Exceptions
{ // class that runs the code
// 1.) Create a Scanner from the inputFilename. Catch exceptions from errors.
// 2.) Read the first String from the file and use it to create a PrintStream
// catching appropriate exceptions
// 3.) Using hasNextInt and nextInt, carefully read the count integer.
// I recommend -1 for a count value if it is bad to indicate reading ALL
// 4.) Use copyNumbers method described below to complete the job
// 5.) Close Scanner and PrintStream objects
// 6.) Call printToScreen to copy the output file to the screen
void process(String inputFilename)
{ // method that does the processing of the file
int number_to_read = 0;
File file = new File(inputFilename); // reading it to a file as the input form is a string name
try
{
String outputFilename;
PrintStream os;
try (Scanner input = new Scanner(file))
{ // checking or reading the unput file
outputFilename = input.next();
os = new PrintStream(new FileOutputStream(outputFilename)); // saving the firstline to a output
filename
if (input.hasNextInt())
{ // checking for the data in the file
number_to_read = input.nextInt();
} else
{
number_to_read = -1;
}
copyNumbers(input, os, number_to_read);
}
os.close(); // closing the stream class
printToScreen(outputFilename); // calling the method to print the data from the output file
} catch (FileNotFoundException e)
{ // catching the exceptions
System.out.println("Cannot find file: " + e);
}
}
// The following routine is called to complete the job of copying integers to
// the output file:
// scan - a Scanner object to copy integers from
// ps - A PrintStream to write the integers to
// numIntsToRead - number of integers to read. A value of -1 ==> read all integers
void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead)
{ // method to copy the data to the file
// hasNext() can be used to see if the scan object still has data
// Note that hasNextInt() can be used to see if an integer is present
// nextInt() will read an integer
// next() can be used to skip over bad integers
if (numIntsToRead < 0)
{
//print out a complaint message and then read as many integers as you find.
System.out.println("A Message Indicating that reading all the data from the file.");
while(scan.hasNextInt())
{
int readNum = scan.nextInt();
ps.print(readNum);
ps.print(" ");
ps.flush();
System.out.println(" Completed Reading the Data.! ");
}
}
else if (!scan.hasNextInt())
{
// print a complaint message and skip over the data
System.out.println(" No Data Present in the File to Read.! ");
scan.nextLine();
}
else
{
for(int i = 0; i < numIntsToRead; i++)
{
if(scan.hasNextInt())
{
int x = scan.nextInt();
ps.println(x);
}
else
{
System.out.println("There was a total of " + i + " ints found, and a total of " +
numIntsToRead + " specified to read. Reading has completed.");
}
}
}
}
public static void main(String[] args)
{
Reading_With_Exceptions rwe = new Reading_With_Exceptions();
for (int i=0; i < args.length; i++)
{
System.out.println("  =========== Processing "+ args[i] + " ========== ");
rwe.process(args[i]);
}
}
// For the last step, we Copy the contents of the file to the screen
private void printToScreen(String filename)
{ // method to print the data to the screen
Scanner scan = null;
try
{
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
System.out.println("Data Present in the Output File is :  ");
while (scan.hasNextLine())
{
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e)
{
System.out.println("printToScreen: can't open: " + filename);
} finally
{
if (scan != null)
{
scan.close();
}
}
}// end of printToScreen
}
/*
file1.txt
MyOutput1.txt 22
20 1 4 5 7 8 9 10 11 12 13 14
45 46 47 48 49 50 51
1 2 3 4 5 6 7 8 9 77 88 99 23 34
56 99 88 77 66 55 44 33 22 11
compile: javac Reading_With_Exceptions.java
run: java Reading_With_Exceptions file1.txt
=========== Processing 1.txt ==========
Data Present in the Output File is :
20
1
4
5
7
8
9
10
11
12
13
14
45
46
47
48
49
50
51
1
2
3
MyOutput1:
20
1
4
5
7
8
9
10
11
12
13
14
45
46
47
48
49
50
51
1
2
3
*/

More Related Content

Similar to Need help with this java code. fill in lines where needed. Also, not.pdf

Can someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdfCan someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdf
fedosys
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
wilcockiris
 
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
fashionbigchennai
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
theodorelove43763
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
Muhammed Thanveer M
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
aquacare2008
 

Similar to Need help with this java code. fill in lines where needed. Also, not.pdf (20)

Can someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdfCan someone put this code in a zip file. I tried running it last tim.pdf
Can someone put this code in a zip file. I tried running it last tim.pdf
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
 
Qtp launch
Qtp launchQtp launch
Qtp launch
 
Satz1
Satz1Satz1
Satz1
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
 
Io files and web
Io files and webIo files and web
Io files and web
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-filesBioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
File management
File managementFile management
File management
 
15. text files
15. text files15. text files
15. text files
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdf
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 

More from rishabjain5053

write a short essay report to describe a topic of your interest rela.pdf
write a short essay report to describe a topic of your interest rela.pdfwrite a short essay report to describe a topic of your interest rela.pdf
write a short essay report to describe a topic of your interest rela.pdf
rishabjain5053
 
What is the nipah virus Describe mechanism of infection How is it .pdf
What is the nipah virus Describe mechanism of infection How is it .pdfWhat is the nipah virus Describe mechanism of infection How is it .pdf
What is the nipah virus Describe mechanism of infection How is it .pdf
rishabjain5053
 
Padre, Inc., buys 80 percent of the outstanding common stock of Sier.pdf
Padre, Inc., buys 80 percent of the outstanding common stock of Sier.pdfPadre, Inc., buys 80 percent of the outstanding common stock of Sier.pdf
Padre, Inc., buys 80 percent of the outstanding common stock of Sier.pdf
rishabjain5053
 
Operating Systems Structure1- Explain briefly why the objectives o.pdf
Operating Systems Structure1- Explain briefly why the objectives o.pdfOperating Systems Structure1- Explain briefly why the objectives o.pdf
Operating Systems Structure1- Explain briefly why the objectives o.pdf
rishabjain5053
 
IP has no mechanism for error reporting or error-correcting. ICMPv4 .pdf
IP has no mechanism for error reporting or error-correcting. ICMPv4 .pdfIP has no mechanism for error reporting or error-correcting. ICMPv4 .pdf
IP has no mechanism for error reporting or error-correcting. ICMPv4 .pdf
rishabjain5053
 
in roughly 400 words please describe3 affective outcomes of diver.pdf
in roughly 400 words please describe3 affective outcomes of diver.pdfin roughly 400 words please describe3 affective outcomes of diver.pdf
in roughly 400 words please describe3 affective outcomes of diver.pdf
rishabjain5053
 
Im having issues with two homework questions. I get the gist of th.pdf
Im having issues with two homework questions. I get the gist of th.pdfIm having issues with two homework questions. I get the gist of th.pdf
Im having issues with two homework questions. I get the gist of th.pdf
rishabjain5053
 
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdfImplement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
rishabjain5053
 

More from rishabjain5053 (20)

write a short essay report to describe a topic of your interest rela.pdf
write a short essay report to describe a topic of your interest rela.pdfwrite a short essay report to describe a topic of your interest rela.pdf
write a short essay report to describe a topic of your interest rela.pdf
 
Write a C++ program to do the followingProject Name Computer Sho.pdf
Write a C++ program to do the followingProject Name Computer Sho.pdfWrite a C++ program to do the followingProject Name Computer Sho.pdf
Write a C++ program to do the followingProject Name Computer Sho.pdf
 
Which statement pertaining to Port Scanning is FALSEA technique use.pdf
Which statement pertaining to Port Scanning is FALSEA technique use.pdfWhich statement pertaining to Port Scanning is FALSEA technique use.pdf
Which statement pertaining to Port Scanning is FALSEA technique use.pdf
 
When did almost all animal phyla divergeSolutionAccording to .pdf
When did almost all animal phyla divergeSolutionAccording to .pdfWhen did almost all animal phyla divergeSolutionAccording to .pdf
When did almost all animal phyla divergeSolutionAccording to .pdf
 
What is the nipah virus Describe mechanism of infection How is it .pdf
What is the nipah virus Describe mechanism of infection How is it .pdfWhat is the nipah virus Describe mechanism of infection How is it .pdf
What is the nipah virus Describe mechanism of infection How is it .pdf
 
What is organizational inertia List some sources of inertia in a co.pdf
What is organizational inertia List some sources of inertia in a co.pdfWhat is organizational inertia List some sources of inertia in a co.pdf
What is organizational inertia List some sources of inertia in a co.pdf
 
Use fundamental identities to write tan t sec2t in terms of sint only.pdf
Use fundamental identities to write tan t sec2t in terms of sint only.pdfUse fundamental identities to write tan t sec2t in terms of sint only.pdf
Use fundamental identities to write tan t sec2t in terms of sint only.pdf
 
Twenty-five people responded to a questionnaire about what types of p.pdf
Twenty-five people responded to a questionnaire about what types of p.pdfTwenty-five people responded to a questionnaire about what types of p.pdf
Twenty-five people responded to a questionnaire about what types of p.pdf
 
The universe began 13 7 billion years ago, is most directly an exa.pdf
The universe began 13 7 billion years ago,  is most directly an exa.pdfThe universe began 13 7 billion years ago,  is most directly an exa.pdf
The universe began 13 7 billion years ago, is most directly an exa.pdf
 
The Stevens Company provided $57000 of services on acco.pdf
The Stevens Company provided $57000 of services on acco.pdfThe Stevens Company provided $57000 of services on acco.pdf
The Stevens Company provided $57000 of services on acco.pdf
 
The papillae on the tongue that do not contain any taste buds are the.pdf
The papillae on the tongue that do not contain any taste buds are the.pdfThe papillae on the tongue that do not contain any taste buds are the.pdf
The papillae on the tongue that do not contain any taste buds are the.pdf
 
QUESTION 13 Which of the following benefits is a component of Social .pdf
QUESTION 13 Which of the following benefits is a component of Social .pdfQUESTION 13 Which of the following benefits is a component of Social .pdf
QUESTION 13 Which of the following benefits is a component of Social .pdf
 
Padre, Inc., buys 80 percent of the outstanding common stock of Sier.pdf
Padre, Inc., buys 80 percent of the outstanding common stock of Sier.pdfPadre, Inc., buys 80 percent of the outstanding common stock of Sier.pdf
Padre, Inc., buys 80 percent of the outstanding common stock of Sier.pdf
 
Operating Systems Structure1- Explain briefly why the objectives o.pdf
Operating Systems Structure1- Explain briefly why the objectives o.pdfOperating Systems Structure1- Explain briefly why the objectives o.pdf
Operating Systems Structure1- Explain briefly why the objectives o.pdf
 
IP has no mechanism for error reporting or error-correcting. ICMPv4 .pdf
IP has no mechanism for error reporting or error-correcting. ICMPv4 .pdfIP has no mechanism for error reporting or error-correcting. ICMPv4 .pdf
IP has no mechanism for error reporting or error-correcting. ICMPv4 .pdf
 
Informed Consent is a significant requirement for all provider types.pdf
Informed Consent is a significant requirement for all provider types.pdfInformed Consent is a significant requirement for all provider types.pdf
Informed Consent is a significant requirement for all provider types.pdf
 
In the MVC Architecture, why is it important to keep the model, view.pdf
In the MVC Architecture, why is it important to keep the model, view.pdfIn the MVC Architecture, why is it important to keep the model, view.pdf
In the MVC Architecture, why is it important to keep the model, view.pdf
 
in roughly 400 words please describe3 affective outcomes of diver.pdf
in roughly 400 words please describe3 affective outcomes of diver.pdfin roughly 400 words please describe3 affective outcomes of diver.pdf
in roughly 400 words please describe3 affective outcomes of diver.pdf
 
Im having issues with two homework questions. I get the gist of th.pdf
Im having issues with two homework questions. I get the gist of th.pdfIm having issues with two homework questions. I get the gist of th.pdf
Im having issues with two homework questions. I get the gist of th.pdf
 
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdfImplement the interface you wrote for Lab B (EntryWayListInterface)..pdf
Implement the interface you wrote for Lab B (EntryWayListInterface)..pdf
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

Need help with this java code. fill in lines where needed. Also, not.pdf

  • 1. Need help with this java code. fill in lines where needed. Also, not sure how to make the text files and load them into program. Thanks!! Create a package named "reading_with_exceptions". Write a class named: Reading_With_Exceptions with the following method: void process(String inputFilename) Your program will encounter errors, and we want you to gracefully handle them in such a way that you print out informative information and continue executing. Your process routine will try to open a file with the name of inputFilename for input. If there is any problem (i.e. the file doesn't exist), then you should catch the exception, give an appropriate error and then return. Otherwise, your program reads the file for instructions. Your process routine will read the first line of the file looking for an outputFilename String followed by an integer. i.e.: outputFilename number_to_read Your program will want to write output to a file having the name outputFilename. Your program will try to read from "inputFilename" the number of integers found in "number_to_read". Your process method will copy the integers read from inputFilename and write them to your output file(i.e. outputFilename). There should contain 10 numbers per line of output in your output file. If you encounter bad input, your program should not die with an exception. For example: If the count of the numbers to be read is bad or < 0 you will print out a complaint message and then read as many integers as you find. If any of the other numbers are bad, print a complaint message and skip over the data If you don't have enough input numbers, complain but do not abort After you have processed inputFilename, I would like your program to then close the output file and tell the user that the file is created. Then Open up the output file and copy it to the Screen. For example, if inputFilename contained: We would expect the output of your program to be (Note that after 23 numbers we stop printing numbers): The main program will access the command line to obtain the list of filenames to call your process routine with. For those of you who benefit from a Template, your program might look like: To prove that your program works, I want you to run your program with the following command line parameters:
  • 2. file1.txt non-existent-file file2.txt file3.txt Where non-existent-file does not exist. file1.txt contains: file2.txt contains: file3.txt contains: Solution // Reading_With_Exceptions.java import java.io.File; // required imports for the code import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class Reading_With_Exceptions { // class that runs the code // 1.) Create a Scanner from the inputFilename. Catch exceptions from errors. // 2.) Read the first String from the file and use it to create a PrintStream // catching appropriate exceptions // 3.) Using hasNextInt and nextInt, carefully read the count integer. // I recommend -1 for a count value if it is bad to indicate reading ALL // 4.) Use copyNumbers method described below to complete the job // 5.) Close Scanner and PrintStream objects // 6.) Call printToScreen to copy the output file to the screen void process(String inputFilename) { // method that does the processing of the file int number_to_read = 0; File file = new File(inputFilename); // reading it to a file as the input form is a string name try { String outputFilename; PrintStream os; try (Scanner input = new Scanner(file)) { // checking or reading the unput file outputFilename = input.next();
  • 3. os = new PrintStream(new FileOutputStream(outputFilename)); // saving the firstline to a output filename if (input.hasNextInt()) { // checking for the data in the file number_to_read = input.nextInt(); } else { number_to_read = -1; } copyNumbers(input, os, number_to_read); } os.close(); // closing the stream class printToScreen(outputFilename); // calling the method to print the data from the output file } catch (FileNotFoundException e) { // catching the exceptions System.out.println("Cannot find file: " + e); } } // The following routine is called to complete the job of copying integers to // the output file: // scan - a Scanner object to copy integers from // ps - A PrintStream to write the integers to // numIntsToRead - number of integers to read. A value of -1 ==> read all integers void copyNumbers(Scanner scan, PrintStream ps, int numIntsToRead) { // method to copy the data to the file // hasNext() can be used to see if the scan object still has data // Note that hasNextInt() can be used to see if an integer is present // nextInt() will read an integer // next() can be used to skip over bad integers if (numIntsToRead < 0) { //print out a complaint message and then read as many integers as you find. System.out.println("A Message Indicating that reading all the data from the file."); while(scan.hasNextInt()) { int readNum = scan.nextInt();
  • 4. ps.print(readNum); ps.print(" "); ps.flush(); System.out.println(" Completed Reading the Data.! "); } } else if (!scan.hasNextInt()) { // print a complaint message and skip over the data System.out.println(" No Data Present in the File to Read.! "); scan.nextLine(); } else { for(int i = 0; i < numIntsToRead; i++) { if(scan.hasNextInt()) { int x = scan.nextInt(); ps.println(x); } else { System.out.println("There was a total of " + i + " ints found, and a total of " + numIntsToRead + " specified to read. Reading has completed."); } } } } public static void main(String[] args) { Reading_With_Exceptions rwe = new Reading_With_Exceptions(); for (int i=0; i < args.length; i++) { System.out.println(" =========== Processing "+ args[i] + " ========== "); rwe.process(args[i]);
  • 5. } } // For the last step, we Copy the contents of the file to the screen private void printToScreen(String filename) { // method to print the data to the screen Scanner scan = null; try { FileInputStream fis = new FileInputStream(filename); scan = new Scanner(fis); System.out.println("Data Present in the Output File is : "); while (scan.hasNextLine()) { System.out.println(scan.nextLine()); } } catch (FileNotFoundException e) { System.out.println("printToScreen: can't open: " + filename); } finally { if (scan != null) { scan.close(); } } }// end of printToScreen } /* file1.txt MyOutput1.txt 22 20 1 4 5 7 8 9 10 11 12 13 14 45 46 47 48 49 50 51 1 2 3 4 5 6 7 8 9 77 88 99 23 34
  • 6. 56 99 88 77 66 55 44 33 22 11 compile: javac Reading_With_Exceptions.java run: java Reading_With_Exceptions file1.txt =========== Processing 1.txt ========== Data Present in the Output File is : 20 1 4 5 7 8 9 10 11 12 13 14 45 46 47 48 49 50 51 1 2 3 MyOutput1: 20 1 4 5 7