Post

Created by @nathanedwards
 at October 31st 2023, 3:33:04 pm.

AP Computer Science Exam Question

Consider the following code snippet:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class FileOperations {

    public static void main(String[] args) {
        File file = new File("sample.txt");

        // Insert code snippet here
    }
}

Write a Java code snippet to answer the following questions:

(a) Write a code snippet to check if the file "sample.txt" exists in the current directory. If it exists, output "File exists". Otherwise, output "File not found".

(b) Write a code snippet to create a new directory named "data" in the current directory.

(c) Write a code snippet to create a new file named "output.txt" inside the "data" directory, and write the text "Hello, World!" into it.

(d) Write a code snippet to read the contents of the "output.txt" file and print them to the console.

Answer

(a) To check if the file "sample.txt" exists in the current directory, you can use the exists() method of the File class. Here's the code snippet to implement it:

if (file.exists()) {
    System.out.println("File exists");
} else {
    System.out.println("File not found");
}

(b) To create a new directory named "data" in the current directory, you can use the mkdir() method of the File class. Here's the code snippet to implement it:

File dataDirectory = new File("data");
dataDirectory.mkdir();

(c) To create a new file named "output.txt" inside the "data" directory and write the text "Hello, World!" into it, you can use the createNewFile() method of the File class and the writeString() method of the Files class. Here's the code snippet to implement it:

File outputFile = new File("data/output.txt");
try {
    outputFile.createNewFile();
    Files.writeString(outputFile.toPath(), "Hello, World!");
} catch (IOException e) {
    e.printStackTrace();
}

(d) To read the contents of the "output.txt" file and print them to the console, you can use the readString() method of the Files class. Here's the code snippet to implement it:

try {
    String outputText = Files.readString(outputFile.toPath());
    System.out.println(outputText);
} catch (IOException e) {
    e.printStackTrace();
}

Please note that proper exception handling is essential in real-world applications.