Код собирается, но при этом выдаёт ошибку Error: Could not find or load main class

Не могу понять, почему код собирается но при этом пишет ошибку что не видит главного класса, хотя сам класс "мейн" присутствует в коде.

ModifyXMLFile.java

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ModifyXMLFile {

    public static void main(String argv[]) {

       try {
        String filepath = "C:\\mita\\Test_kod\\file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

       //Get the root element
        Node company = doc.getFirstChild();

       //Get the staff element , it may not working if tag has spaces, or
       //whatever weird characters in front...it's better to use
       //getElementsByTagName() to get it directly.
       //Node staff = company.getFirstChild();

       //Get the staff element by tag name directly
        Node staff = doc.getElementsByTagName("staff").item(0);

       //update staff attribute
        NamedNodeMap attr = staff.getAttributes();
        Node nodeAttr = attr.getNamedItem("id");
        nodeAttr.setTextContent("2");

       //append a new node to staff
        Element age = doc.createElement("age");
        age.appendChild(doc.createTextNode("28"));
        staff.appendChild(age);

       //loop the staff child node
        NodeList list = staff.getChildNodes();

        for (int i = 0; i < list.getLength(); i++) {

                   Node node = list.item(i);

          //get the salary element, and update the value
           if ("salary".equals(node.getNodeName())) {
            node.setTextContent("2000000");
           }

                  //remove firstname
           if ("firstname".equals(node.getNodeName())) {
            staff.removeChild(node);
           }

        }

       //write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");

       } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
       } catch (TransformerException tfe) {
        tfe.printStackTrace();
       } catch (IOException ioe) {
        ioe.printStackTrace();
       } catch (SAXException sae) {
        sae.printStackTrace();
       }
    }
}

file.xml

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<company>
   <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>100000</salary>
   </staff>
</company>

Вот вывод

C:\mita\Test_kod>javac ModifyXMLFile.java

C:\mita\Test_kod>java -classpath . ModifyXMLFile.class
Error: Could not find or load main class ModifyXMLFile.class

Попробовал вот так, но, увы не вышло :

C:\mita\Test_kod>java -mainpath . DOMxmlEdit.class
Unrecognized option: -mainpath
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

C:\mita\Test_kod>java -classpath main DOMxmlEdit.class
Error: Could not find or load main class DOMxmlEdit.class

C:\mita\Test_kod>java -classpath . DOMxmlEdit.class
Error: Could not find or load main class DOMxmlEdit.class

Ответы (1 шт):

Автор решения: Pak Uula

java требует для запуска имя класса, а не путь к файлу.

Ваша команда должна выглядеть вот так: java -classpath . ModifyXMLFile

Команда java -classpath . ModifyXMLFile.class просит запустить класс с именем class в пакете ModifyXMLFile. Разумеется, такого объекта нет, о чем вам и сообщают в ошибке.


Вот так надо делать:

C:\mita\Test_kod>java -classpath . ModifyXMLFile
Done

после чего появляется файл lenguageUpdated.xml с таким содержанием:

<<?xml version="1.0" encoding="UTF-8" standalone="no"?><company>
<staff id="2">
 
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>2000000</salary>
<age>28</age></staff>
</company>
→ Ссылка