So I was given a code about IO to understand

// The "FileIO" class.
import java.awt.*;
import hsa.Console;
import java.io.*;

public class FileIO
{
    static Console c;           // The output console

    public void writeFile ()
    {
        PrintWriter output;
        String fileName;

        c.println ("Saving a File in Java!");
        c.print ("Enter file name: ");
        fileName = c.readLine ();

        try
        {
            output = new PrintWriter (new FileWriter (fileName));
            c.println ("The message is outputting to your monitor.");
            output.println ("\"This message is saving to a file.\"");

            output.close ();
        }//
        catch (IOException e)
        {
        }
    }


    public void readFile ()
    {
        String fileName, line = "";
        BufferedReader input;

        c.println ("Reading a File in Java!");
        c.print ("Enter a file name: ");
        fileName = c.readLine ();

        try
        {
            input = new BufferedReader (new FileReader (fileName));
            line = input.readLine ();
        }
        catch (IOException e)
        {
        }
        c.println ("The line in the file " + fileName + " is " + line);

    }


    public static void main (String[] args)
    {
        c = new Console ();
        FileIO d;
        d = new FileIO();
        d.writeFile();
        d.readFile();

    } // main method
} // FileIO class

So what I understand from this is that the method writeFile() is saving the file with the name entered by the user and the method readFile() reads the file. Right? But when I input myfile2 as the filename and new for reading the file it works and invokes ouput. I don't get how that works.

Recommended Answers

All 3 Replies

So what I understand from this is that the method writeFile() is saving the file with the name entered by the user and the method readFile() reads the file. Right?

Right.

But when I input myfile2 as the filename and new for reading the file it works and invokes ouput.

Can you explain that again please - it doesn't seem to make any sense.

Let's say I save the file as myfile2 and then I want to read a file named new. It still reads myfile2 even though I wanted new.

I think I figured it out. It's because its lacking an if statement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.