0

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?

8
  • 3
    Why do you think there's something wrong? Are you getting an error or the wrong output? Commented Oct 29, 2014 at 15:36
  • y will hold the number of added elements. To access the last one you have to use y-1 in the get call. Commented Oct 29, 2014 at 15:39
  • The output I get is "Empty." instead of "Hello, World". Commented Oct 29, 2014 at 15:39
  • 1
    You may have to close the out stream before reading from that file. Commented Oct 29, 2014 at 15:40
  • 4
    you need to out.close() first to commit your changes to the file Commented Oct 29, 2014 at 15:40

3 Answers 3

2

1) You need to close the stream

2) You need to refer to the x Arraylist with (y-1) otherwise you will get a java.lang.IndexOutOfBoundsException . The indexes starts from 0 and not from 1.

http://www.tutorialspoint.com/java/util/arraylist_get.htm

   public static void main(String[] args) throws FileNotFoundException
        {
            PrintWriter out = new PrintWriter("hello.txt");
            out.println("Hello, World");
            out.close();
            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++;
            }

            in.close();  

            if (x.size() == 0)
            {
                System.out.println("Empty.");
            }
            else
            {
                System.out.println(x.get(y-1));
            }

        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I guess what's wrong with the code ist that you cant read anything from the file.

this is because PrintWriter is buffered

fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

You need to close the file you have just writen to before openning it for reading so that the changes are fluched to the physical storage. Thus moving out.close(); right after out.println("Hello, World");

Comments

0
class FileWritingDemo {
public static void main(String [] args) {
char[] in = new char[13]; // to store input
int size = 0;
try {
File file = new File("MyFile.txt"); // just an object

FileWriter fw = new FileWriter(file); // create an actual file & a FileWriter obj
fw.write("Hello, World!"); // write characters to the file
fw.flush(); // flush before closing
fw.close(); // close file when done

FileReader fr = new FileReader(file); // create a FileReader object
size = fr.read(in); // read the whole file!
for(char c : in) // print the array
System.out.print(c);
fr.close(); // again, always close
} catch(IOException e) { }
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.