What is the result?

Given that myfile.txt contains:

First

Second

Third

Given the following code fragment:

public class ReadFile02 {

public static void main(String[] args) {

String fileName1 = “myfile.txt”;

String fileName2 = “newfile.txt”;

try (BufferedReader buffIn =

new BufferedReader(new FileReader(fileName1));

BufferedWriter buffOut =

new BufferedWriter(new FileWriter(fileName2))

) {

String line = “”; int count = 1;

line = buffIn.readLine();

while (line != null) {

buffOut.write(count + “: ” + line);

buffOut.newLine();

count++;

line = buffIn.readLine();

}

} catch (IOException e) {

System.out.println(“Exception: ” + e.getMessage());

}

}

}

What is the result?

Given that myfile.txt contains:

First

Second

Third

Given the following code fragment:

public class ReadFile02 {

public static void main(String[] args) {

String fileName1 = “myfile.txt”;

String fileName2 = “newfile.txt”;

try (BufferedReader buffIn =

new BufferedReader(new FileReader(fileName1));

BufferedWriter buffOut =

new BufferedWriter(new FileWriter(fileName2))

) {

String line = “”; int count = 1;

line = buffIn.readLine();

while (line != null) {

buffOut.write(count + “: ” + line);

buffOut.newLine();

count++;

line = buffIn.readLine();

}

} catch (IOException e) {

System.out.println(“Exception: ” + e.getMessage());

}

}

}

What is the result?

A.
new file.txt contains:
1: First
2: Second
3: Third

B.
new file.txt contains:
1: First 2: Second 3: Third

C.
newfile.txt is empty

D.
an exception is thrown at runtime

E.
compilation fails

Explanation:
For each line in the file myfile.text the line number and the line is written into newfile.txt.



Leave a Reply 3

Your email address will not be published. Required fields are marked *


Ls

Ls

The answer is A without considering the buffOut has not be closed.

Tim

Tim

buffOut is also auto-closed via the try-with-resource mechanism.