Question: 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!