I need to write a pixel array to disk and read that file back in the same application. For some reason, the files don't write to disk until the application terminates. (Only then do they show up in the directory to which they're saved). I'm writing this application in IntelliJ IDEA if that is in any way useful to know.
How do I ensure that the file is written to disk immediately? Here is my code:
protected void savePixelstoPNG(int[] pixels, String fileName) {
BufferedImage image = new BufferedImage(getMapWidth(), getMapHeight(), BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
for(int y = 0; y < getMapHeight(); y++) {
for(int x = 0; x < getMapWidth(); x++) {
graphics.setColor(new Color(pixels[x + y * getMapWidth()]));
graphics.fillRect(x, y, 1, 1);
}
}
try {
File file = new File(fileName);
ImageIO.write(image, "PNG", file);
} catch(IOException e) {
e.printStackTrace();
}
}
EDIT: I inspected the folders and they in fact ARE being written immediately to disk. However, these changes are NOT reflected in the project directory (The files are saved into a java package) until the application terminates. So when I go to read those files after saving them (within the same application lifetime) the application can't find the files, even though they exist on disk.
EDIT 2: Here is the code that I'm using to read the file from the classpath using a relative directory path. The initial resources are read from the classpath. When they are updated, they are written to different directory in the classpath so the original resources are not overwritten, since the original resources are supposed to be initially read each time the application is run anew:
void myLoadMethod() {
loadMapTiles("resource/tilemap_1-1.png");
loadTriggerTiles("resource/triggermap_1-1.png");
}
protected void loadMapTiles(@NotNull String path) {
URL url = getClass().getClassLoader().getResource(path);
loadTiles(url, mapTiles);
}
protected void loadTriggerTiles(@NotNull String path) {
URL url = getClaass().getClassLoader().getResource(path);
loadTiles(url, triggerTiles);
}
protected void loadTiles(@NotNull URL url, @Nullable int[] dest) {
try {
System.out.println("Trying to load: " + url.toString() + "...");
BufferedImage map = ImageIO.read(url);
int[] pixels = new int[mapWidth * mapHeight];
map.getRGB(0, 0, mapWidth, mapHeight, pixels, 0, mapWidth);
System.arraycopy(pixels, 0, dest, 0, dest.length);
System.out.println("Success!");
} catch (IOException e) {
System.out.println("failed...");
e.printStackTrace();
}
}
}
Note that mapTiles
and triggerTiles
are fields contained within the class that holds loadMapTiles
loadTriggerTiles
and loadTiles