0

Completely new to programming and studying it right now at a university. This might seem easy but they literally showed us nothing on how to program so this task is hard for me to do. So maybe someone here can help me understand how I can do this:

The task:

  1. Create a method called "open(String fileName)" that creates and opens a text file with the name fileName
  2. Create a method called "pageStart()" that writes "html" into the file

There are a lot more methods I have to create but all of them should be easy if I understand how the "pageStart()" one works.

package exporter;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class HTMLCreator {

    public static void main(String[] args) {
    open("Hello.txt");

    }

    public static void open(String fileName) {

    File file = new File(fileName);

    try {
        // Creates new file
        if (file.createNewFile()) {
        }

        // Opens file
        Desktop desktop = Desktop.getDesktop();
        if (file.exists())
        desktop.open(file);
    } catch (IOException e) {
        e.printStackTrace();
        }
    }
}

Ok so that does create a .txt file and opens it. So far so good. Now the problem. I have to create a method that WRITES into that .txt file and I have NO clue how to do that.

What I tried until now:

public static void startPage() {
    FileWriter fw = new FileWriter(file)/*<-- obviously won't work but I don't know how it would work...*/; 
    fw.write("<html>");
    fw.close();
    }

I know that this obviously won't work since the file that I want is not in that method. How do I do that?

How do I make it so my startPage() method writes into the Hello.txt file I created earlier?

I would appreciate help a lot!!!

My question is not about how to create and write into a textfile! My question is more how you combine two methods to do this! It would help immensely if someone could write two methods for me, one that creates and opens a textfile and another method that writes into the textfile that the first method created and opened. That would most likely solve my problem!

  • Possible duplicate of [How do I create a file and write to it in Java?](https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it-in-java) – Emily Nov 17 '19 at 17:15
  • Nope. My problem here is more a "how do you combine two methods" then a "how to create and write into a file" problem. I know how to write into the text file. I just don't know how to write into the text file with a seperate method. – Pennervomland Nov 17 '19 at 17:50

0 Answers0