尝试创建我的第一个可执行jar并且正在使用Maven这样做。
Java本身运行正常,但是当我尝试运行jar时,我得到src \ main \ resources \ sound.wav的FileNotFoundException。
我认为问题显然在pom.xml文件和资源声明中,但是我对maven和jars缺乏经验以及缺乏想法意味着无论我摆弄多少,我似乎都无法修复它做。
我的pom.xml文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupID</groupId>
<artifactId>Main</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<finalName>MailCheck</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>sound.wav</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>package-jar-with-dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>Main</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
我的Java文件如下所示:
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import javax.mail.*;
import javax.mail.search.FlagTerm;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Main {
public static void main(String[] args)
{
String password = "mypassword";
String emailAddress = "myemail";
String soundFile = "src\\main\\resources\\sound.wav";
AudioStream as = null;
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
InputStream in = new FileInputStream(soundFile);
as = new AudioStream(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
Session session = Session.getInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", emailAddress, password);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] messages = inbox.search(ft);
int unreadMail = 0;
for (Message message : messages)
{
unreadMail++;
if (unreadMail > 0)
{
AudioPlayer.player.start(as);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
包后,此文件应存在于生成的JAR中。请检查一下。此外,您不能像文件系统中的普通文件那样在JAR中获取InputStream
文件。您应该尝试从资源中获取InputStream
。
InputStream in = Main.class.getClassLoader()
.getResourceAsStream("src/main/resources/sound.wav");