Skip to content
Snippets Groups Projects
IndexReader.java 2.43 KiB

package koz01.java2.lab08;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

import javafx.scene.image.Image;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class IndexReader {

	private static final String URL = "http://kozusznik.cz/resources/java2/";
	private static final String IMAGE_NAME = "lab08.imgs";

	public Image readImage(int index) {

		try (FileChannel fc = FileChannel.open(getFile()))
		{
			byte[] data = getData(fc, index);
			return new Image(new ByteArrayInputStream(data));
		}
		catch (IOException exc) {
			log.error("read", exc);
			return null;
		}

	}

	private Path getFile() throws IOException {
		Path LocalFile = Files.createTempFile(null, null).getParent().resolve(
			IMAGE_NAME);
		if (!Files.exists(LocalFile)) {
			try (ReadableByteChannel in = Channels.newChannel(new URL(
				URL + IMAGE_NAME).openStream());
					FileChannel out = FileChannel.open(LocalFile,
						StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))
			{
				ByteBuffer bb = ByteBuffer.allocate(1024 * 1024);
				while (0 <= in.read(bb)) {
					bb.flip();
					out.write(bb);
					bb.clear();
				}
			}
		}
		return LocalFile;
	}

	private byte[] getData(FileChannel fc, int i) throws IOException {
		// 0...3 - number of images
		// 4 ... 7 - Position of 1. image data in file
		// 8 ... 11 - Lenght of 1. image

		// position_in_index = 4 + i*8

		// position_of_image = readInt(position_in_index)
		// size_of_image = readInt(position_in_index + 4)

		// data = readData(position_of_image, size_of_image)
		// return data
		// go to position ... fc.position(position)
		// read data .... fc.read(bb) - bb is ByteBuffer

		// create ByteBuffer 8 bytes long
		ByteBuffer bb = ByteBuffer.allocate(8);
		fc.position(0);
		fc.read(bb);
		bb.flip();
		int numberOfImages = bb.getInt();
		if (i < 0 || numberOfImages <= i) {
			return new byte[0];
		}
		bb.clear();
		fc.position(4 + i * 8);
		fc.read(bb);
		bb.flip();
		int position = bb.getInt();
		int size = bb.getInt();

		bb = ByteBuffer.allocate(size);
		fc.position(position);
		fc.read(bb);
		bb.flip();
		return bb.array();

		// read data .... fc.read(bb) - bb is ByteBuffer
		// bb.flip()
		// bb.getInt(), bb.getInt()


	}
}