Java Program doesn't work after exported from eclipse - java

When I open the runnable jar file, it still could be opened but it get stuck after half a second like this.
(I cannot post an image, so I post the image here: https://pbs.twimg.com/media/B4RN2_MCYAAi1DD.png)
It works well in eclipse.
When I run it in CMD, it says:
Exception in thread "game" java.lang.NullPointerException: in
at javazoom.jl.decoder.Bitstream.<init>(Unknown Source)
at javazoom.jl.player.Player.<init>(Unknown Source)
at javazoom.jl.player.Player.<init>(Unknown Source)
at lian.xiangru.game.AudioHandler.<init>(AudioHandler.java:12)
at lian.xiangru.game.GameBoard.playSound(GameBoard.java:410)
at lian.xiangru.game.GameBoard.move(GameBoard.java:224)
at lian.xiangru.game.GameBoard.moveTiles(GameBoard.java:271)
at lian.xiangru.game.GameBoard.checkKeys(GameBoard.java:340)
at lian.xiangru.game.GameBoard.update(GameBoard.java:146)
at lian.xiangru.game.Game.update(Game.java:42)
at lian.xiangru.game.Game.run(Game.java:77)
at java.lang.Thread.run(Unknown Source)
It seems something goes wrong with my resources.
This is my playSound method:
private void playSound() {
// how to play mp3 https://www.youtube.com/watch?v=f-7cgX_I220
AudioHandler sound = new AudioHandler(
SOUND_LIST[(int) Math.round((Math.log(highestValue) / Math.log(2))) - 1]);
sound.start();
}
This is my AudioHandler class:
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
class AudioHandler extends Thread {
private Player playMP3;
public AudioHandler(String mp3) {
try {
playMP3 = new Player(getClass().getResourceAsStream(mp3));
} catch (JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
playMP3.play();
} catch (JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The lists are:
public static final String[] SOUND_LIST = { "/mayuri.mp3", "/mikoto.mp3",
"/gai.mp3", "/shougo.mp3", "/gintoki.mp3", "/inori.mp3",
"/yuzuru.mp3", "/misaki.mp3", "/armin.mp3", "/alphonse.mp3",
"/alphonse.mp3", "/akane.mp3", "/armin.jpg" };
public static final String[] QUOTE_LIST = { "/mayuri.txt", "/mikoto.txt",
"/gai.txt", "/shougo.txt", "/gintoki.txt", "/inori.txt",
"/yuzuru.txt", "/misaki.txt", "/armin.txt", "/alphonse.txt",
"/alphonse.txt", "/akane.txt", "/armin.txt" };
public static final String[] ICON_LIST = {"/mayuri.jpg", "/mikoto.jpg",
"/gai.jpg", "/shougo.jpg", "/gintoki.jpg", "/inori.jpg",
"/yuzuru.jpg", "/misaki.jpg", "/armin.jpg", "/alphonse.jpg",
"/alphonse.jpg", "/akane.jpg", "/armin.jpg"
};
Thank you !!

NullPointerException when loading a resource usually means that the resource could not be found. This behavior is different than the normal file open, no exception is thrown.
Are your audio files included in your jar? If not, make sure that when you export the Jar, you set the right options so they are included. A better alternative might be to introduce a real build process into your application if you need repeatability.

I just found the reason!
There is a file called Mikoto.mp3 in my resources folder and I typed it as mikoto.mp3 in my code. This could be allowed when I use eclipse to run it. But when I run the runnable jar file, it fails because it is case sensitive.
When I change the file name to mikoto.mp3, it works!
Thanks for your answer!

Related

Desktop.getDesktop().open(file) on Ubuntu not working

I have a Java application, and when I use java.awt.Desktop:
Desktop.getDesktop().open(file);
It works fine on Windows (opens a file in my default program), but on Ubuntu (with openJdk 13), the Java application gets stuck and I do not even get any log error or anything. I have to force quit the app in order to recover.
The file path it correct, otherwise I would actually get an Exception. Also, isDesktopSupported a isSupported(Action.OPEN) returns true.
What can I do? Can I check some system settings or logs? Or perhaps get some logs from java.awt.Desktop? Or does this not work on Ubuntu/Linux?
Are there any alternatives?
From here:
In order to use the API, you have to call java.awt.EventQueue.invokeLater() and call methods of the Desktop class from a runnable passed to the invokeLater():
void fxEventHandler() {
EQ.invokeLater(() -> {
Desktop.open(...);
});
}
I am just going to add an example function
private static void OpenFile(String filePath){
try
{
//constructor of file class having file as argument
File file = new File(filePath);
if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not
{
System.out.println("not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) { //checks file exists or not
EventQueue.invokeLater(() -> {
try {
desktop.open(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

File not found java ini4j

I am trying to write something to a ini file using ini4j.
When i call the store() method it throws a FileNotFound exception even though it is in my project directory.
Maybe i did something wrong with my code?
Main:
public class Main {
public static Wini ini = null;
public static void main(String[] args) {
Config conf = new Config();
try {
conf.setMultiOption(true);
ini = new Wini();
ini.setConfig(conf);
ini.load(new File("apikeys.ini"));
} catch (InvalidFileFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The file where i attempt to write and store the data:
if (KeyEndpoint.isValid(apikey)) {
Main.ini.put(apikey, Main.ini.get("Apikey"));
try {
Main.ini.store();
} catch (IOException e) {
channel.sendMessage("Invalid api key.").queue();
}
} else {
channel.sendMessage("API Key is invalid.").queue();
}
Any help is appreciated, I at least want to know what I am doing wrong.
Thanks!
It has to do with relative paths. Try changing the filename in Main for the absolute path, something like "/tmp/apikeys.ini", to check that your code works correctly. If that works, then you can now change it to either something like "../../directory/filename" or something relative to where you know you're executing your code from. Get familiar with your java path environment variables such as JAVA_HOME and all to get it to something more permanent and portable.

Files.copy returns empty file when jar is exported

The file downloads properly in eclipse however when i export the jar it always downloads a blank exe. Can anyone help?
public static void downloadAndRunFile(final URL from, final File to) throws Exception {
try (final InputStream in = from.openStream()) {
Files.copy(in, to.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(to);
}
Actual code being ran
String bub = "https://a.coka.la/bnH6Vg.exe";
try {
Pandora.downloadAndRunFile(
new URL(bub),
File.createTempFile("feelthevluci", ".exe"));
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
The URL in your code seems to return a 404.
I changed it to something that I know works and is safe, and that works both in the IDE and in a jar file.
Check the URL via curl, browser, or other tool to make sure it is working.

javax.media.NoPlayerException: Cannot find a Player for wav files in jar

I use Java Media Framework 2.1.1 for playing sounds in my application. It works fine from IDE but once I make jar package. The Player objects cannot be initialized with exception:
javax.media.NoPlayerException: Cannot find a Player for :jar:file:...
I create players using javax.media.Manager.createPlayer(URL sourceURL) method. I suspect that the URL from jar is causing the problems.
Is there an alternative way how to construct the player with files from jar?
Code:
public SoundPlayer() {
urlExplosion = ResourceLoader.getInstance().getSoundResourceUrl(SoundResource.EXPLOSION);
urlTick = ResourceLoader.getInstance().getSoundResourceUrl(SoundResource.TICK);
urlWin = ResourceLoader.getInstance().getSoundResourceUrl(SoundResource.WIN);
}
public void initialize() throws ResourceLoadingException{
try {
explosionPlayer = Manager.createPlayer(urlExplosion);
explosionPlayer.realize();
tickPlayer = Manager.createPlayer(urlTick);
tickPlayer.realize();
winPlayer = Manager.createPlayer(urlWin);
winPlayer.realize();
} catch (NoPlayerException e) {
throw new ResourceLoadingException("Could not initialize the sound player",e);
} catch (IOException e) {
throw new ResourceLoadingException("Could not initialize the sound player",e);
}
isInitialized = true;
}
Note: the URLs are no null during runtime.
Error when run from command line: java -jar minesweeper.jar
Caused by: javax.media.NoPlayerException: Cannot find a Player for :jar:file:/path/to/app/minesweeper.jar!/my/package/minesweeper/gui/explosion.wav

IOException: Read Error

If you want more info on the error, the full source can be downloaded here
Hey, I'm reading an ini file using java.util.Properties; and I've run into a strange issue. When I try to load a specific file, the thing spits out this strange exception that I've been trying for about a day to eliminate.
java.io.IOException: Read error
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(Unknown Source)
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at IniReader.load(IniReader.java:20)
at plane.<init>(plane.java:22)
at renderingArea.<init>(flight_optimizer.java:93)
at flight_optimizer_GUI.<init>(flight_optimizer.java:159)
at flight_optimizer.main(flight_optimizer.java:46)
I had previously been reading this file just fine with no problems, I then changed a bit of how I was calling and had to add an extra line at the bottom. If I remove that line, the problem does not occour.
the txt file is:
x=0
y=0
max_velocity=.1
passengers=100
num_planes=1
If I remove the num_planes=1 line, the file gets read fine.
Relevant code:
import java.util.Enumeration;
public class IniReader {
//global vars
public IniReader(){
// initializeing stuffs
}
public void load(InputStream inStream) throws IOException {
this.inStream = inStream;
this.properties.load(this.inStream);
this.keys = this.properties.propertyNames();
inStream.close();
}
}
class renderingArea extends JPanel {
//Global vars
private IniReader ini;
public renderingArea(){
super();
// Initializing some things
files = new fileManager();
ini = new IniReader();
FileInputStream planeStream;
FileInputStream cityStream;
try {
planeStream = files.getIni("plane.ini");
ini.load(planeStream);
//extraneous code
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (NumberFormatException e1) {
e1.printStackTrace();
}
}
//moar extraneous code
}
That is why:
Your code (flight_optimizer.java, line 82 and further):
FileInputStream planeStream;
...
planeStream = files.getIni("plane.ini");
ini.load(planeStream);
...
for( int i=0; i<planes.length; i++ ){
planes[i] = new plane(planeStream);
}
Both the second line and every cycle iteration leads us here (IniReader.java, line 17):
public void load(InputStream inStream) throws IOException {
this.inStream = inStream;
this.properties.load(this.inStream);
this.keys = this.properties.propertyNames();
inStream.close();
}
You are trying to use the same InputStream multiple times, moreover, you are trying to use it after it already was closed. You will need to recreate the stream, or, preferably, read configuration once and use it multiple times.
As a side note, the recommended way to use the streams in Java is the following:
InputStream is = ...;
try {
// Reading from the stream
} finally {
is.close();
}
This will make sure that the system resources associated with the stream will always be released.
I had the same problem. Turns out that my underlying InputStream was already closed. That became obvious when I ran my test under Linux, where a more meaningful error message was emitted by the operating system.

Categories

Resources