I have a super beginner's question. I have a computer science test today and one of the practice problems is this:
- Write a program that carries out the following tasks:
- Open a file with the name hello.txt.
- Store the message “Hello, World!” in the file.
- Close the file.
- Open the same file again.
- Read the message into a string variable and print it.
This is the code I have for it so far:
import java.util.*;
import java.io.*;
public class ReadFile
{
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y));
}
in.close();
out.close();
}
}
What's wrong with this code?
out.close()first to commit your changes to the file