Question

Part 2: Programming with Exceptions In this part of the lab , you will write a...

Part 2: Programming with Exceptions In this part of the lab

, you will write a program that fetches the information stored at a give URL on the web and saves that data to a file. This will also include networking and file operations and partly an exercise in using exceptions. For doing I/O, Java has a pair of nice abstractions: InputStream and OutputStream. These are abstract classes in the package java.io. An InputStream is a place from which you can read data; an OutputStream is a place to which you can write data. For this lab, you will use an InputStream to represent the data read from the Web URL, and you will use an OutputStream to represent the file where you want to save a copy of the data. Once you have the streams, the data can be copied just by calling the following method, which you can copy into your program: private static void copyStream(InputStream in, OutputStream out) throws IOException { int oneByte = in.read(); while (oneByte >= 0) { // negative value indicates end-of-stream out.write(oneByte); oneByte = in.read(); } } Aside from this method, you should have a main routine that does the following: Declare variables to represent the InputStream and the OutputStream. It would be a good idea to initialize them to null to avoid uninitialized variable errors. Read the URL and the file name as strings from the user. To connect to the web, you need a variable -- say url -- of type URL (from package java.io). You can create the URL object with the constructor call url = new URL(urlString), where urlString is the string provided by the user. This constructor will throw a MalformedURLException if the string is not a legal URL. (Note: the string must be a complete URL, beginning with "http://".) To get the input stream, you can simply call url.openStream(), which returns a value of type InputStream. This can throw an IOException, for example, if the web address that you are asking for does not exist. To get the output stream, you can use the constructor new FileOutputStream(fileName), where fileName is the file name that was input by the user. This can throw a FileNotFoundException if it is not possible to open the specified file for reading (for example, if the user is trying to create a new file in a directory where they don't have write permission). Warning: If a file of the same name already exists, the old file will be erased and replaced by the new one, without giving the user any notice! Now, copy the data from the web into the file by calling the above method. Note that this can throw an IOException. Finally, use a finally to clause to make sure that both streams are closed (if they were successfully opened). Both InputStream and OutputStream have a close() method for closing the stream. Note that you can test whether the stream was opened by testing whether the value of the variable is still null. Note that an exception should not crash your program. You should catch the exception and print out a reasonable error message before ending the program. It would be nice if the error message depends on the type of error that occurred (which means using several catch clauses).

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class asdfasdf {
   public static void main(String[] args) throws MalformedURLException, IOException {
       Scanner sc = new Scanner(System.in);
      
       //taking url from user to fetch data
       System.out.print("Enter URL: ");
       String urlString = sc.nextLine();
      
       //taking output file name to write data to output file name
       System.out.print("Enter Output FileName: ");
       String outputFileName = sc.nextLine();
      
       //this is code to copy data from url to output file
   BufferedInputStream in = null;
   FileOutputStream fout = null;
   try {
   in = new BufferedInputStream(new URL(urlString).openStream());
   fout = new FileOutputStream(outputFileName);

   final byte data[] = new byte[1024];
   int count;
   while ((count = in.read(data, 0, 1024)) != -1) {
   fout.write(data, 0, count);
   }
   } finally {
   if (in != null) {
   in.close();
   }
   if (fout != null) {
   fout.close();
   }
   }
   //display end result to console
   System.out.println("Output has writen to "+outputFileName);
   }
}

Add a comment
Know the answer?
Add Answer to:
Part 2: Programming with Exceptions In this part of the lab , you will write a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This last lab teaches you to think and solve problems in the functional programming framework of...

    This last lab teaches you to think and solve problems in the functional programming framework of the Java 8 computation streams. Therefore in this lab, you are absolutely forbidden to use any conditional statements (either if or switch), loops (either for, while or do-while) or even recursion. All computation must be implemented using only computation streams and their operations! In this lab, we also check out the Java NIO framework for better file operations than those offered in the old...

  • Using the diagram below and the starter code, write Document Processor that will read a file...

    Using the diagram below and the starter code, write Document Processor that will read a file and let the user determine how many words of a certain length there are and get a count of all of the word lengths in the file. Your program should do the following: The constructor should accept the filename to read (word.txt) and then fill the words ArrayList up with the words from the file. The countWords method should accept an integer that represents...

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

  • Lab 10: ArrayLists and Files in a GUI Application For this lab, you will work on...

    Lab 10: ArrayLists and Files in a GUI Application For this lab, you will work on a simple GUI application. The starting point for your work consists of four files (TextCollage, DrawTextItem, DrawTextPanel, and SimpleFileChooser) in the code directory. These files are supposed to be in package named "textcollage". Start an Eclipse project, create a package named textcollage in that project, and copy the four files into the package. To run the program, you should run the file TextCollage.java, which...

  • Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written...

    Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written to a file. Each line of the input file will contain the student name (a single String with no spaces), the number of semester hours earned (an integer), the total quality points earned (a double). The following shows part of a typical...

  • Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB:...

    Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB: Step 0 - Getting Starting In this program, we have two classes, FileIO.java and FileReader.java. FileIO.java will be our “driver” program or the main program that will bring the file reading and analysis together. FileReader.java will create the methods we use in FileIO.java to simply read in our file. Main in FileIO For this lab, main() is provided for you in FileIO.java and contains...

  • Can anyone help me? Thank you very much. Question 10 1 pts The constructor below is...

    Can anyone help me? Thank you very much. Question 10 1 pts The constructor below is very similar to the one you used for the last assignment. What is its time complexity in terms of N, where N is the number of lines in the Input Stream (the word file)? public Doublets (Inputstream in) try t lexicon. new TreeSet String O; Scanner s new Scanner (new BufferedReader new I (in))) while (s hasNext String str s next boolean added lexicon....

  • Your assignment is to write a grade book for a teacher. The teacher has a text file, which includ...

    Your assignment is to write a grade book for a teacher. The teacher has a text file, which includes student's names, and students test grades. There are four test scores for each student. Here is an example of such a file: Count: 5 Sally 78.0 84.0 79.0 86.0 Rachel 68.0 76.0 87.0 76.0 Melba 87.0 78.0 98.0 88.0 Grace 76.0 67.0 89.0 0.0 Lisa 68.0 76.0 65.0 87.0 The first line of the file will indicate the number of students...

  • Reading and Writing Complete Files in C: The first part of the lab is to write...

    Reading and Writing Complete Files in C: The first part of the lab is to write a program to read the complete contents of a file to a string. This code will be used in subsequent coding problems. You will need 3 functions: main(), read_file() and write_file(). The main function contains the driver code. The read_file() function reads the complete contents of a file to a string. The write_file() writes the complete contents of a string to a file. The...

  • (Java) Rewrite the following exercise below to read inputs from a file and write the output...

    (Java) Rewrite the following exercise below to read inputs from a file and write the output of your program in a text file. Ask the user to enter the input filename. Use try-catch when reading the file. Ask the user to enter a text file name to write the output in it. You may use the try-with-resources syntax. An example to get an idea but you need to have your own design: try ( // Create input files Scanner input...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT