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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started