0

For my Software Engineering class I am required to use maven to create an SVG file. At the moment I have my only java file in main class looking like this:

import java.io.File;  // Import the File class
import java.io.FileWriter;
import java.io.IOException;  // Import the IOException class to handle errors

    public class CreateFile {
      public static void main(String[] args) {
        try {
          File myObj = new File("tester22.svg");
          if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
          } else {
            System.out.println("File already exists.");
          }
        } catch (IOException e) {
          System.out.println("An error occurred.");
          e.printStackTrace();
        }
          try {
            FileWriter myWriter = new FileWriter("tester.svg");
            myWriter.write("Files in Java might be tricky, but it is fun enough!");
            myWriter.close();
            System.out.println("Successfully wrote to the file.");
          } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
          }
      }
    }

However, when I run maven test it does not generate the tester22.svg file. I am not sure how to make it create the file as when I run that java file on its own it has no problem creating the file.

EDIT: when I run mvn test, everything comes back successful and there seems to be no problems.

SRJ
  • 2,092
  • 3
  • 17
  • 36
  • `mvn test` won't run your main method. To run the main class using maven you can run `mvn exec:java -Dexec.mainClass="com.example.Main"`. – SRJ Feb 12 '21 at 05:43
  • @ShubhWIP is there any possible way to make it so that mvn test will run that? And thank you very much that helps so much already! – FisherC Feb 12 '21 at 05:50
  • Does this answer your question? [Maven Run Project](https://stackoverflow.com/questions/1089285/maven-run-project) – SRJ Feb 12 '21 at 06:49

1 Answers1

0

You can include exec-maven-plugin plugin to invoke your main class during maven build/test phase.

For e.g.

  • In your pom.xml, Add Plugin exec-maven-plugin or alternatively copy below code
  • Specify your full path of main class inside <mainClass> element.
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <mainClass>com.baeldung.main.Exec</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build

Add exec:java along with your mvn test command to run your main method along with your tests.

Reference : https://www.baeldung.com/maven-java-main-method

SRJ
  • 2,092
  • 3
  • 17
  • 36