gpt4 book ai didi

java - 无法运行具有 .jar 依赖项的 Java 应用程序 - 'Error: Could not find or load main class'

转载 作者:行者123 更新时间:2023-12-02 02:59:02 25 4
gpt4 key购买 nike

所以我的代码在 IDE 中运行良好,并且我将 javax.mail.jar 设置为依赖项,并且我的代码运行良好。

除非我需要使用Console console = System.console();这在 IDE 中不起作用

所以我尝试编译我的代码并通过终端运行它,我可以编译,尽管在运行我的代码时它返回错误:

Error: Could not find or load main class Main

这就是我要编译的内容:

javac -cp "./javax.mail.jar" Main.java

然后运行它:

java -cp "./javax.mail.jar" Main

但我收到错误:无法找到或加载主类 Main

这是我的完整代码:

package com.company;

import java.io.IOException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {
public static void main(String[] args) throws IOException {


Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("TestEmail@gmail.com","pass");
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("TestEmail@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("TestEmail@gmail.com"));
message.setSubject("JavaMail");
message.setText("Hi," + "\n\n This is a test");

Transport.send(message);

System.out.println("Sent!");


} catch (MessagingException e) {
throw new RuntimeException(e);
}
}


}

编辑:还尝试从父目录运行(其中有我的 com 文件夹和 java.mail.jar):

java -cp "./javax.mail.jar;." com.company.Main

但我明白了:

Error: Could not find or load main class com.company.Main

最佳答案

您应该从 com 的父文件夹编译它,方法是:

javac -cp "./javax.mail.jar:." com/company/Main.java

然后运行

java -cp "./javax.mail.jar:." com.company.Main

关于java - 无法运行具有 .jar 依赖项的 Java 应用程序 - 'Error: Could not find or load main class',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42637209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com