I am trying to load a map with the bukkit API, and ran into a problem.
The map does not load. The file gets created and get cappied as well, but when i do /memory in game, it shows all the loaded worlds, and this does not show up. And when i try to teleport to the world by doing p.teleport(world.getSpawnLocation()); it just throws a java.lang.NullPointerException: null execption.
my code:
public static void loadMap(String l) throws IOException {
try {
File folderName = new File(plugin.getDataFolder() + "/maps/Dungeon");
File desti = new File(l + "_world");
if(!desti.exists()) {
desti.mkdir();
}
FileUtils.copyDirectory(folderName, desti);
World world = Bukkit.getServer().createWorld(new WorldCreator(l + "_world"));
System.out.println("[DDEBUG]" + world);
} catch (Exception e) {
System.out.println(e);
}
}
Any ideas on how to fix this ?
that means the player is null, so it throws this error
btw. if you use try and catch blok, so remove throws IOException
Related
I'm working on a text-based RPG with some friends using Netbeans. It works all fine and dandy in Netbeans but when I export it to a .jar file I get this error.
Jan 28, 2019 2:27:15 PM Operator.DragonsHead startActionPerformed
SEVERE: null
java.io.FileNotFoundException: File "src\Operator\files\Opening.mid" does not exist!
This happens when the game starts, as we have a "theme" that plays at boot up.
The song plays on Netbeans but not when exported.
I'm relatively new to Java programming, I took a course on it last year.
I've tried looking around the web for people having the same issue, but I can't quite get it to duplicate with my code.
Here's the midi class:
import javax.sound.midi.*;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
public class MIDI {
private File file = null;
private Sequencer sequencer = null;
public MIDI (String midiFile) throws FileNotFoundException {
this.file = new File(midiFile);
if (!file.isFile()) {
throw new FileNotFoundException("File \"" + midiFile + "\" does not exist!");
}
try{
sequencer = MidiSystem.getSequencer();
if (sequencer == null){
System.err.println("Error: Sequencer not supported");
return;
}
sequencer.open();
Sequence sequence = MidiSystem.getSequence(file);
sequencer.setSequence(sequence);
}
catch (MidiUnavailableException | InvalidMidiDataException | IOException ex){
}
}
public void play(){
sequencer.start();
}
public void stop() {
sequencer.stop();
}
public void waitAndStop(int millis) {
Runnable song = () -> {
try {
Thread.sleep(millis);
}
catch (InterruptedException e) {
System.err.println("MIDI playback interrupted");
}
stop();
};
Thread t = new Thread(song);
t.start();
}
public long songLengthMicroseconds() {
return sequencer.getMicrosecondLength();
}
public Sequence getSequence(String resource) {
try {
return MidiSystem.getSequence(new File(resource));
}
catch (InvalidMidiDataException | IOException ex) {
return null;
}
}
}
Here's the lines that initialize it and call the song to play:
MIDI midiTest;
midiTest = new MIDI("src\\Operator\\files\\Opening.mid");
midiTest.play();
I'm not sure what the API is of 'MIDI', but unless you want to go through the rigamarole of writing an installer, you cannot use direct file access for resources like icons, pictures, music, and datafiles.
Instead, use the getResource/getResourceAsStream mechanism, which returns URLs/InputStreams. Well written libraries take these just as well as files.
Basic format:
try (InputStream resource = MyClassName.class.getResourceAsStream("Opening.mid")) {
// do something with resource here.
}
where Opening.mid is in the exact same place that MyClassName.class is (so, if you are shipping as a jar, it's in the jar, in the same folder structure as myClassName.class. If you prefer to have a root dir 'music' in your jar, you can pass for example: /music/Opening.mid, with the leading slash to indicate you're going off of the jar root.
secondary observation, if you don't know what to do with an exception, best solution is to add the exception(s) you cannot handle to your method's 'throws' line. If that is somehow not possible, the proper body for a catch block is:
throw new RuntimeException("unhandled checked exception", e);
because right now if an error occurs, your code will silently just keep going. If that was your intent (because, hey, music is optional I guess), I'd still log it SOMEWHERE, right now if an error occurs, you just won't know about it.
I have a strange bug when executing my code. The first time I save the level, the code properly writes to the file. Upon running the game, the level is properly loaded. However, the second time I try saving on a level that was previously loaded, the save file's arraylists become null. The code DOES NOT throw an error, I noticed only the ArrayList filled with entities, not the level itself, became null, hence does not properly load the game the second time around.
Here is my code:
public void save() {
try (ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(fileName, false))) {
out.writeObject(object);
} catch (IOException e) {
System.out.println("There was a problem saving " + object);
System.out.println(e.getMessage());
}
}
public Object load() {
try (ObjectInputStream in = new ObjectInputStream(
new FileInputStream(fileName))) {
return in.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("There was a problem loading " + object);
System.out.println(e.getMessage());
}
return null;
}
The following methods are called when expected:
public static void saveGame() {
level.save();
System.out.println("SAVED");
System.out.println(level.load());
}
public static void load() {
if (level.load() != null) {
Level.level1 = (Level) level.load();
System.out.println(Level.level1);
System.out.println("LOADED");
}
}
The levels themselves are static, I'm not sure if that has any special rules. Here is the snippet of the Level instance data if that is needed:
protected List<Mob> mobs = new CopyOnWriteArrayList<Mob>();
protected List<Player> players = new CopyOnWriteArrayList<Player>();
private String imagePath;
private transient BufferedImage image;
public static Level level1 = new LordHillsboroughsDomain();
I have a feeling it has something to do with a new instance of the level overwriting the saved level, but I just can't seem to figure it out. Any help is greatly appreciated!
I am very new to StackOverflow and I've done my best to fix this problem before posting this question here. I'm faced with the problem of getResource() returning null. I have a hunch that this is because I'm on a mac and the pathing is different here than on a PC (where this code seems to work fine). This is the code:
public class SampleClass
{
static String imgpath = "/theimage.png";
public static void main(String[] args)
{
System.out.println(imgpath);
System.out.println(SampleClass.class.getResource(imgpath));
try
{
BufferedImage image = ImageIO.read(SampleClass.class.getResource(imgpath));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
src, res and bin are all in the same directory and theimage.png is inside of res.
System.out.println(SampleClass.class.getResource("imgpath")); gives me null.
I had the same issue on my mac using spring boot :
the file is located on properties/report/example.jasper
when the path was : "report/example.jasper" i got nullPointerException
So i changed to : "./report/example.jasper" and It works fine without any bug.
InputStream inStream = null;
try {
inStream = ExportController.class.getClassLoader().getResourceAsStream(path);
final JasperReport jasperReport = (JasperReport) JRLoader.loadObject(inStream);
jasperReport.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
} catch (final JRException jre) {
throw new TechnicalException("Error when export jasper");
} finally {
if (inStream != null) {
inStream.close();
}
}
you get nullpointer exception because there is no image named imgpath in that folder
public class SampleClass
{
static String imgpath = "/theimage.png";
public static void main(String[] args)
{
System.out.println(imgpath);
System.out.println(SampleClass.class.getResource(imgpath));
try
{
BufferedImage image = ImageIO.read(SampleClass.class.getResource(imgpath));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I faced the same issue on Mac. Here how I now get files from resources. For example, I have a common Maven project with resource folder in src/main. In resource folder I have a file "test.txt".
To get a path to the file:
public class Utils {
public static String getFilePathInResources() {
URL url = Utils.class.getClassLoader().getResource("test.txt");
return url.getPath();
}
}
Here the filename is hardcored just for clearity, of course, really it is a parameter in the method.
If set a filename as "/test.txt" with "/" - this will give null.
URL url = Utils.class.getClassLoader().getResource("/test.txt"); // url == null
I am having trouble with returning string array on a client and server environment. The result I getting is nothing when I compiled the client application.
server application
public String[] getFlight() throws Exception {
AvailableFlights todayFlight = new AvailableFlights();
List<Flight> flights_today = todayFlight.getFlightDetail();
List<String> flights = new ArrayList<String>();
try {
flights_today = this.unmarshal(new File("Flights.xml"));
for (Flight flight : flights_today) {
String flightDetail = flight.getJourney()
+ " " + flight.getAirline()
+ " "+ String.valueOf(flight.getConnections())
+ " "+ String.valueOf(flight.getCost())
+ " "+ flight.getDestination()
+ " "+ flight.getOrigin()
+ " "+ String.valueOf(flight.getSeats());
flights.add(flightDetail);
System.out.println(flightDetail);
}
} catch (Exception e) {
}
return (String[]) flights.toArray();
}
client java application
import org.me.kettravel.*;
public class JavaApplication5 {
public static void main(String[] args) {
try {
System.out.println(getFlight());
} catch (Throwable ex) {
}
}
private static java.util.List<java.lang.String> getFlight() throws Exception_Exception {
org.me.kettravel.ReadFlightService service = new org.me.kettravel.ReadFlightService();
org.me.kettravel.ReadFlight port = service.getReadFlightPort();
return port.getFlight();
}
Additionally I have tried a small experiment with "hello" like below on the server app and it worked fine, so I know that the web service is working fine but I just can't seem to pass/return the flights String array to the client app.
String i = "hello";
return i;
PS: When I try to run the server app with public static void main (String[] args) { constructor and without return, the app printed out the arraylist perfectly from unmarshalling xml convert it to arraylist and do system.out.print.
I would be grateful if anyone could shed some light as I am really stuck on this. Thanks.
04/01/2012 (19:16) - Adjustment has been made suggested by Genzer, the client app still not getting any response from server app.
04/01/2012 (23:24) - Adjustment has been made suggested by Bohemian can be seen below, the client app is now getting an error checking javax.xml.ws.soap.SOAPFaultException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
public static void main(String[] args) {
try {
Object obj = getFlight();
System.out.println(obj);
} catch (Throwable ex) {
System.out.println(ex);
}
}
06/01/2013 (16:20) - I have just addressed my mistake as the XML file was empty from tests to tests, however it is now have data in the xml file. I have just created a test class to see if readFlight returns anything to a class that it's in a same project/source package. Result is a success... really running out of ideas =/ as I have tested the web service by sending a simple hello string over to client app and worked no problem.
test class
public class test {
public static void main(String[] args) {
readFlight rF = new readFlight();
try {
System.out.println(rF.getFlight());
} catch (Throwable ex) {
System.out.println(ex);
}
}
}
Output from the test class: [London to Amsterdam KLM 1 200.0 Amsterdam London 100, London to Kuala Lumper Malaysia Airline 1 750.0 Kuala Lumper London 100, London to Manchester British Airway 1 50.0 Manchester London 56]
10/01/2013 (18:13) - PROBLEM SOLVED. You have to give full directory to the unmarshall file. Example: C:/Users/User/Documents/NetBeansProjects/WebService/booking.xml
The problem is that you have two different variables named flights. You populate one and return the other.
You could remove public static String[] flights and modify the method like this:
public List<String> getFlight() throws Exception {
Flight nextFlight = new Flight();
AvailableFlights todayFlight = new AvailableFlights();
List<Flight> flights_today = todayFlight.getFlightDetail();
// Since you you List for Flight, why not here
List<String> flights = new ArrayList<String>();
try {
flights_today = readFlight.unmarshal(new File("Flights.xml"));
for (Flight flight : flights_today) {
String flightDetail = flight.getJourney()
+ " " + flight.getAirline()
+ " "+ String.valueOf(flight.getConnections())
+ " "+ String.valueOf(flight.getCost())
+ " "+ flight.getDestination()
+ " "+ flight.getOrigin()
+ " "+ String.valueOf(flight.getSeats());
flights.add(flightDetail);
}
} catch (Exception e) {
}
return flights;
}
You have committed a "no no", which may be hiding the problem:
catch (Exception e) {
}
You should never (well, rarely) catch Exception. Especially when your catch block is empty.
There could be an unchecked exception, like NullPointerException, being thrown within your loop, but you wouldn't know.
Try removing the catch and leaving only soecific Exceptions (if any) that are declared to be thrown.
If one of the method is declared as throwing Exception, then at the very least, you should do this:
catch (Exception e) {
System.out.println(e);
}
Basically, I am trying to generate a log file in Robocode, but I am having issues as you cannot use try/catch in Robocode (as far as I am aware). I have done the following:
public void onBattleEnded(BattleEndedEvent e) throws IOException
{
writeToLog();
throw new IOException();
}
and
public void writeToLog() throws IOException
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new IOException();
}
and am getting the following error at compile time:-
MyRobot.java:123: onBattleEnded(robocode.BattleEndedEvent) in ma001jh.MyRobot cannot implement onBattleEnded(robocode.BattleEndedEvent) in robocode.robotinterfaces.IBasicEvents2; overridden method does not throw java.io.IOException
public void onBattleEnded(BattleEndedEvent e) throws IOException
^
1 error
As you can see here, the interface doesn't declare any checked exceptions. So you can't throw one in your implementing class.
One way to solve this would be to implement your method like this:
public void onBattleEnded(BattleEndedEvent e)
{
writeToLog();
throw new RuntimeException(new IOException());
}
public void writeToLog()
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new new RuntimeException(new IOException());
}
but I am having issues as you cannot use try/catch in Robocode (as far as I am aware)
Where did this assumption came from? I just because of your question here installed robocode (so it's your fault if I'll answer here less often in future), wrote my own robot and it can catch exceptions quite good:
try {
int i = 1/0;
}
catch(ArithmeticException ex) {
ex.printStackTrace();
}
And why are you throwing IOExceptions in your example?