Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

In Java Below is an example of a noncompliant piece of code. void readData() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(file)));

In Java

Below is an example of a noncompliant piece of code.

void readData() throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("file")));

// Read from the file

String data = br.readLine();

}

The objective is to create two programs that replicate this function but are compliant. Below are two codes that do this.

import java.io.*;

public class Main {

public static void main(String[] args) { BufferedReader br = null; try { String data;

br = new BufferedReader(new FileReader("file.txt")); while ((data = br.readLine()) != null) { System.out.println(data); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }

import java.io.*;

public class Main {

private static final String FNAME = "file.txt";

public static void main(String[] args) {

try (BufferedReader b = new BufferedReader(new FileReader(FNAME))) {

String data;

while ((data = b.readLine()) != null) {

System.out.println(data);

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

Please respond with recommendations on making these two codes more compliant. Also, please respond with how the changes made to these two codes make them more compliant than the original code. Thank you.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Microsoft SQL Server 2012 Unleashed

Authors: Ray Rankins, Paul Bertucci

1st Edition

0133408507, 9780133408508

More Books

Students also viewed these Databases questions

Question

What are the classifications of Bank?

Answered: 1 week ago

Question

8. Praise the trainees for their success in learning the task.

Answered: 1 week ago