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.
Related
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();
}
}
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.
I try to load a property file in Java running on JBossFuse/karaf.
The file is located at $[karaf.home]/etc/bean.properties
The Code is able to load properties inside the bundle fine, but now I try to exclude the properties from the project itself and the code throws a Nullpointer-Exception.
The Path is properly resolved on my development machine as
C:\Users\someone\devstudio\runtimes\jboss-fuse-6.3.0.redhat-135\etc\bean.properties
The property-File can be loaded in the blueprint-XML to configure beans, but to access the bean my code needs the CamelContext. As I have some static codeblocks that are accessed without an exchange/context/registry, I also wanted to be able to load the properties in Java.
Both the functions throw the NullPointerException and I guess, it is because the code runs in Fuse.
public static Properties getProperties(String location) {
Properties prop = new Properties();
InputStream input = null;
try {
input = PropertyLoader.class.getClassLoader().getResourceAsStream(location);
prop.load(input);
} catch (IOException ex) {
log.error("Error loading properties file from: " + location, ex);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error(e);
}
}
}
return prop;
}
public static Properties getPropertiesFromFilesystem(String location) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(location);
prop.load(input);
} catch (IOException ex) {
log.error("Error loading properties file from: " + location, ex);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error(e);
}
}
}
return prop;
}
The Exception:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)[:1.8.0_91]
at java.util.Properties.load0(Properties.java:353)[:1.8.0_91]
at java.util.Properties.load(Properties.java:341)[:1.8.0_91]
at com.mycompany.util.PropertyLoader.getProperties(PropertyLoader.java:19)[319:camel-archetype-blueprint:0.0.14]
at com.mycompany.camel.blueprint.MyProcessor.process(MyProcessor.java:21)[319:camel-archetype-blueprint:0.0.14]
at org.apache.camel.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:63)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:468)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.Pipeline.process(Pipeline.java:121)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:192)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:76)[231:org.apache.camel.camel-core:2.17.0.redhat-630135]
at java.util.TimerThread.mainLoop(Timer.java:555)[:1.8.0_91]
at java.util.TimerThread.run(Timer.java:505)[:1.8.0_91]
Any help would be highly appreciated.
Do not do that. You are looking for trouble.
Load properties the OSGi way (use .cfg as extension and a blueprint property-placeholder bean)
You have the added benefit of getting notified if the file changes (if you wish)
Inject them in a bean EVEN IF you are using only static methods.
Don't mix managed beans with unmanaged static code unless you know very well what you are doing.
If some "static" code requires properties means that it is stateful, and this class deserves to be instantiated to a bean.
Not sure why you are getting an NPE without a more complete example. If you need to use properties without a route, you should be using Camel's property placeholder facilities:
https://access.redhat.com/documentation/en-us/red_hat_jboss_fuse/6.3/html/apache_camel_development_guide/basicprinciples#BasicPrinciples-PropPlaceholders
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!
(I have a problem that I illustrated in this question but had no correct answers. I refined my problem and tried to edit the initial question to reflect that but I guess because of the way SO displays unanswered questions it lost momentum and there is no way to revive it. So I am posting my correct question again).
I have a file that resides on a shared network location :
"\\KUROSAVVAS-PC\Users\kuroSAVVAS\Desktop\New Folder\Warsaw Panorama.JPG"
(The spaces are there intentionally)
The following code :
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
String s = "\\\\KUROSAVVAS-PC\\Users\\kuroSAVVAS\\Desktop\\New Folder\\Warsaw Panorama.jpg";
File f = new File(s);
System.out.println(f.exists());
Desktop.getDesktop().open(f);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Prints to the console that the file exists (System.out.println(f.exists());) but throws this exception! :
java.io.IOException: Failed to open file:////KUROSAVVAS-PC/Users/kuroSAVVAS/Desktop/New%20%20%20%20%20Folder/Warsaw%20%20%20%20Panorama.jpg. Error message: The system cannot find the file specified.
at sun.awt.windows.WDesktopPeer.ShellExecute(WDesktopPeer.java:59)
at sun.awt.windows.WDesktopPeer.open(WDesktopPeer.java:36)
at java.awt.Desktop.open(Desktop.java:254)
at Test.main(Test.java:13)
Has anyone any idea why something like this may happen? I have tried everything from creating URIs to decoding them afterwards... Nothing works.
With java 7 you can do this
public static void main(String[] args) throws IOException {
String s = "\\\\KUROSAVVAS-PC\\Users\\kuroSAVVAS\\Desktop\\New Folder\\Warsaw Panorama.jpg";
Path p = Paths.get(s);
Desktop.getDesktop().browse(p.toUri());
}
Java 6 solution:
public static void launchFile(File file) {
if (!Desktop.isDesktopSupported())
return;
Desktop dt = Desktop.getDesktop();
try {
dt.open(file);
} catch (IOException ex) {
// this is sometimes necessary with files on other servers ie
// \\xxx\xxx.xls
launchFile(file.getPath());
}
}
// this can launch both local and remote files
public static void launchFile(String filePath) {
if (filePath == null || filePath.trim().length() == 0)
return;
if (!Desktop.isDesktopSupported())
return;
Desktop dt = Desktop.getDesktop();
try {
dt.browse(getFileURI(filePath));
} catch (Exception ex) {
ex.printStackTrace();
}
}
// generate uri according to the filePath
private static URI getFileURI(String filePath) {
URI uri = null;
filePath = filePath.trim();
if (filePath.indexOf("http") == 0 || filePath.indexOf("\\") == 0) {
if (filePath.indexOf("\\") == 0){
filePath = "file:" + filePath;
filePath = filePath.replaceAll("#", "%23");
}
try {
filePath = filePath.replaceAll(" ", "%20");
URL url = new URL(filePath);
uri = url.toURI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
} else {
File file = new File(filePath);
uri = file.toURI();
}
return uri;
}
This answer was on the bug report, but I've edited it to fix when there is a hash.
TL;DR of ZAMMBI's answer (+1 BTW). (Using Java 6)
This works, as expected
Desktop.getDesktop().open(new File("\\\\host\\path_without\\spaces.txt")); //works
This fails, due to a known Java bug:
Desktop.getDesktop().open(new File("\\\\host\\path with\\spaces.txt")); //fails <shakes fist>
This work-around works
Desktop.getDesktop().browse(new URI("file://host/path%20with/spaces.txt")) //works (note slash direction and escape sequences)
This work-around seems like it should work, but does not:
Desktop.getDesktop().browse((new File("\\\\host\\path with\\spaces.txt")).toURI());
This work-around works, and seems to be the most general form:
File curFile = new File("\\\\host\\path with\\or_without\\spaces\\local or network.txt");
Desktop.getDesktop().browse(new URI(curFile .toURI().toString().replace("file:////","file://")));
It seems that there is a bug when you try to access a resource on a network drive with spaces in the path. See this entry in Sun's bug database.
Since the bug is already a year old, I don't think you'll get a fix anytime soon. Try the latest VM. If that doesn't help, try to get the source for WDesktopPeer. Instead of encoding the path, try to keep it as it was (with backslashes and all) and put quotes around it. That might work.
[EDIT] Specifically, don't replace \ with /, do not prepend file:// and leave the spaces as they are (instead of replacing them with %20)