Java Code Examples for com.badlogic.gdx.utils.StreamUtils#closeQuietly()

The following examples show how to use com.badlogic.gdx.utils.StreamUtils#closeQuietly() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DownloadUtil.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
public static byte[] download(String url) throws IOException {
    InputStream in = null;
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(true);
        conn.connect();
        in = conn.getInputStream();
        return StreamUtils.copyStreamToByteArray(in);
    } catch (IOException ex) {
        throw ex;
    } finally {
        StreamUtils.closeQuietly(in);
    }
}
 
Example 2
Source File: AndroidModLoader.java    From Cubes with MIT License 6 votes vote down vote up
public static String hashFile(FileHandle fileHandle) throws Exception {
  InputStream inputStream = fileHandle.read();
  try {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");

    byte[] bytesBuffer = new byte[1024];
    int bytesRead;

    while ((bytesRead = inputStream.read(bytesBuffer)) != -1) {
      digest.update(bytesBuffer, 0, bytesRead);
    }

    byte[] hashedBytes = digest.digest();
    return convertByteArrayToHexString(hashedBytes);
  } catch (IOException ex) {
    throw new CubesException("Could not generate hash from file " + fileHandle.path(), ex);
  } finally {
    StreamUtils.closeQuietly(inputStream);
  }
}
 
Example 3
Source File: Mini2DxOgg.java    From mini2Dx with Apache License 2.0 6 votes vote down vote up
public Sound(Mini2DxOpenALAudio audio, FileHandle file) {
	super(audio);
	if (audio.noDevice)
		return;
	OggInputStream input = null;
	try {
		input = new OggInputStream(file.read());
		ByteArrayOutputStream output = new ByteArrayOutputStream(4096);
		byte[] buffer = new byte[2048];
		while (!input.atEnd()) {
			int length = input.read(buffer);
			if (length == -1)
				break;
			output.write(buffer, 0, length);
		}
		setup(output.toByteArray(), input.getChannels(), input.getSampleRate());
	} finally {
		StreamUtils.closeQuietly(input);
	}
}
 
Example 4
Source File: BehaviorTreeReader.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
/** Parses the given reader.
 * @param reader the reader
 * @throws SerializationException if the reader cannot be successfully parsed. */
public void parse (Reader reader) {
	try {
		char[] data = new char[1024];
		int offset = 0;
		while (true) {
			int length = reader.read(data, offset, data.length - offset);
			if (length == -1) break;
			if (length == 0) {
				char[] newData = new char[data.length * 2];
				System.arraycopy(data, 0, newData, 0, data.length);
				data = newData;
			} else
				offset += length;
		}
		parse(data, 0, offset);
	} catch (IOException ex) {
		throw new SerializationException(ex);
	} finally {
		StreamUtils.closeQuietly(reader);
	}
}
 
Example 5
Source File: D2.java    From riiablo with Apache License 2.0 6 votes vote down vote up
public static D2 loadFromStream(InputStream in) {
  try {
    int numBlocks = Block.MAX_VALUE;
    Block[] blocks = new Block[numBlocks];
    for (int i = 0; i < numBlocks; i++) {
      blocks[i] = new Block(in);
      if (DEBUG_BLOCKS) Gdx.app.debug(TAG, i + ": " + blocks[i].toString());
    }

    return new D2(blocks);
  } catch (Throwable t) {
    throw new GdxRuntimeException("Couldn't load D2 from stream.", t);
  } finally {
    StreamUtils.closeQuietly(in);
  }
}
 
Example 6
Source File: ParseTreeTest.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
public Actor createActor (Skin skin) {
	Reader reader = null;
	try {
		reader = Gdx.files.internal("data/dog.tree").reader();
		BehaviorTreeParser<Dog> parser = new BehaviorTreeParser<Dog>(BehaviorTreeParser.DEBUG_HIGH);
		BehaviorTree<Dog> tree = parser.parse(reader, new Dog("Buddy"));
		treeViewer = createTreeViewer(tree.getObject().name, tree, true, skin);

		return new ScrollPane(treeViewer, skin);
	} finally {
		StreamUtils.closeQuietly(reader);
	}
}
 
Example 7
Source File: BehaviorTreeReader.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
/** Parses the given input stream.
 * @param input the input stream
 * @throws SerializationException if the input stream cannot be successfully parsed. */
public void parse (InputStream input) {
	try {
		parse(new InputStreamReader(input, "UTF-8"));
	} catch (IOException ex) {
		throw new SerializationException(ex);
	} finally {
		StreamUtils.closeQuietly(input);
	}
}
 
Example 8
Source File: PL2.java    From riiablo with Apache License 2.0 5 votes vote down vote up
public static PL2 loadFromStream(InputStream in) {
  try {
    // Skip the internal palette data which was loaded in the corresponding .dat
    IOUtils.skipFully(in, 0x400);

    // TODO: It may be faster to implement using single dimension using offsets
    byte[][] colormaps = new byte[COLORMAPS + TINTS][Palette.COLORS];
    for (int i = 0; i < COLORMAPS; i++) {
      IOUtils.readFully(in, colormaps[i]);
    }

    int available = in.available();
    if (available % TINT_SIZE > 0) {
      throw new GdxRuntimeException("Remaining bytes does not match an expected tint count.");
    }

    final int tintsUsed = available / TINT_SIZE;
    int[] tints = new int[tintsUsed];
    for (int i = 0, r, g, b; i < tintsUsed; i++) {
      r = in.read();
      g = in.read();
      b = in.read();
      tints[i] = (r << 16) | (g << 8) | b;
    }

    // NOTE: LOADING PL2 is missing a tint, so readFully will not work here :/
    for (int i = 0; i < tintsUsed; i++) {
      IOUtils.readFully(in, colormaps[COLORMAPS + i]);
    }

    return new PL2(colormaps, tints);
  } catch (Throwable t) {
    throw new GdxRuntimeException("Couldn't load PL2 from stream.", t);
  } finally {
    StreamUtils.closeQuietly(in);
  }
}
 
Example 9
Source File: Palette.java    From riiablo with Apache License 2.0 5 votes vote down vote up
public static Palette loadFromStream(InputStream in) {
  try {
    byte[] data = new byte[COLORS * 3];
    IOUtils.readFully(in, data);
    return loadFromArray(data);
  } catch (Throwable t) {
    throw new GdxRuntimeException("Couldn't load palette from stream.", t);
  } finally {
    StreamUtils.closeQuietly(in);
  }
}
 
Example 10
Source File: Mini2DxWav.java    From mini2Dx with Apache License 2.0 5 votes vote down vote up
public Sound (Mini2DxOpenALAudio audio, FileHandle file) {
	super(audio);
	if (audio.noDevice) return;

	WavInputStream input = null;
	try {
		input = new WavInputStream(file);
		setup(StreamUtils.copyStreamToByteArray(input, input.dataRemaining), input.channels, input.sampleRate);
	} catch (IOException ex) {
		throw new GdxRuntimeException("Error reading WAV file: " + file, ex);
	} finally {
		StreamUtils.closeQuietly(input);
	}
}
 
Example 11
Source File: Mini2DxOgg.java    From mini2Dx with Apache License 2.0 4 votes vote down vote up
public void reset () {
	StreamUtils.closeQuietly(input);
	previousInput = null;
	input = null;
}
 
Example 12
Source File: Mini2DxOgg.java    From mini2Dx with Apache License 2.0 4 votes vote down vote up
public void reset () {
	StreamUtils.closeQuietly(input);
	previousInput = null;
	input = null;
}
 
Example 13
Source File: Mini2DxOgg.java    From mini2Dx with Apache License 2.0 4 votes vote down vote up
@Override
protected void loop () {
	StreamUtils.closeQuietly(input);
	previousInput = input;
	input = null;
}
 
Example 14
Source File: MPQViewer.java    From riiablo with Apache License 2.0 4 votes vote down vote up
private void readMPQs() {
  if (fileTreeNodes == null) {
    fileTreeNodes = new PatriciaTrie<>();
    fileTreeCofNodes = new PatriciaTrie<>();
  } else {
    fileTreeNodes.clear();
    fileTreeCofNodes.clear();
  }

  BufferedReader reader = null;
  try {
    //if (options_useExternalList.isChecked()) {
      reader = Gdx.files.internal(ASSETS + "(listfile)").reader(4096);
    //} else {
    //  try {
    //    reader = new BufferedReader(new InputStreamReader((new ByteArrayInputStream(mpq.readBytes("(listfile)")))));
    //  } catch (Throwable t) {
    //    reader = Gdx.files.internal(ASSETS + "(listfile)").reader(4096);
    //  }
    //}

    Node<Node, Object, Actor> root = new BaseNode(new VisLabel("root"));
    final boolean checkExisting = options_checkExisting.isChecked();

    String fileName;
    while ((fileName = reader.readLine()) != null) {
      if (checkExisting && !Riiablo.mpqs.contains(fileName)) {
        continue;
      }

      String path = FilenameUtils.getPathNoEndSeparator(fileName).toLowerCase();
      treeify(fileTreeNodes, root, path);

      final MPQFileHandle handle = (MPQFileHandle) Riiablo.mpqs.resolve(fileName);
      VisLabel label = new VisLabel(FilenameUtils.getName(fileName));
      final Node node = new BaseNode(label);
      node.setValue(handle);
      label.addListener(new ClickListener(Input.Buttons.RIGHT) {
        @Override
        public void clicked(InputEvent event, float x, float y) {
          showPopmenu(node, handle);
        }
      });

      String key = fileName.toLowerCase();
      fileTreeNodes.put(key, node);
      if (FilenameUtils.isExtension(key, "cof")) {
        key = FilenameUtils.getBaseName(key);
        fileTreeCofNodes.put(key, node);
      }
      if (path.isEmpty()) {
        root.add(node);
      } else {
        fileTreeNodes.get(path + "\\").add(node);
      }
    }

    sort(root);
    fileTree.clearChildren();
    for (Node child : root.getChildren()) {
      fileTree.add(child);
    }

    fileTree.layout();
    fileTreeFilter.clearText();
  } catch (IOException e) {
    throw new GdxRuntimeException("Failed to read list file.", e);
  } finally {
    StreamUtils.closeQuietly(reader);
  }
}
 
Example 15
Source File: Mini2DxWav.java    From mini2Dx with Apache License 2.0 4 votes vote down vote up
public void reset () {
	StreamUtils.closeQuietly(input);
	input = null;
}
 
Example 16
Source File: FreeTypeFontGenerator.java    From gdx-texture-packer-gui with Apache License 2.0 4 votes vote down vote up
/** Creates a new generator from the given font file. Uses {@link FileHandle#length()} to determine the file size. If the file
 * length could not be determined (it was 0), an extra copy of the font bytes is performed. Throws a
 * {@link GdxRuntimeException} if loading did not succeed. */
public FreeTypeFontGenerator (FileHandle fontFile, int faceIndex) {
	name = fontFile.pathWithoutExtension();
	int fileSize = (int)fontFile.length();

	library = FreeType.initFreeType();
	if (library == null) throw new GdxRuntimeException("Couldn't initialize FreeType");

	ByteBuffer buffer = null;

	try {
		buffer = fontFile.map();
	} catch (GdxRuntimeException e) {
		// Silently error, certain platforms do not support file mapping.
	}

	if (buffer == null) {
		InputStream input = fontFile.read();
		try {
			if (fileSize == 0) {
				// Copy to a byte[] to get the file size, then copy to the buffer.
				byte[] data = StreamUtils.copyStreamToByteArray(input, 1024 * 16);
				buffer = BufferUtils.newUnsafeByteBuffer(data.length);
				BufferUtils.copy(data, 0, buffer, data.length);
			} else {
				// Trust the specified file size.
				buffer = BufferUtils.newUnsafeByteBuffer(fileSize);
				StreamUtils.copyStream(input, buffer);
			}
		} catch (IOException ex) {
			throw new GdxRuntimeException(ex);
		} finally {
			StreamUtils.closeQuietly(input);
		}
	}

	face = library.newMemoryFace(buffer, faceIndex);
	if (face == null) throw new GdxRuntimeException("Couldn't create face for font: " + fontFile);

	if (checkForBitmapFont()) return;
	setPixelSizes(0, 15);
}
 
Example 17
Source File: PNG8.java    From gdx-texture-packer-gui with Apache License 2.0 3 votes vote down vote up
/**
 * Attempts to write the given Pixmap exactly as a PNG-8 image to file; this attempt will only succeed if there
 * are no more than 256 colors in the Pixmap (treating all partially transparent colors as fully transparent).
 * If the attempt fails, this falls back to calling {@link #write(FileHandle, Pixmap, boolean, boolean)}, which
 * can dither the image to use no more than 255 colors (plus fully transparent) based on ditherFallback and will
 * always analyze the Pixmap to get an accurate-enough palette, using the given threshold for analysis (which is
 * typically between 1 and 1000, and most often near 200-400). All other write() methods in this class will
 * reduce the color depth somewhat, but as long as the color count stays at 256 or less, this will keep the
 * non-alpha components of colors exactly.
 * @param file a FileHandle that must be writable, and will have the given Pixmap written as a PNG-8 image
 * @param pixmap a Pixmap to write to the given output stream
 * @param ditherFallback if the Pixmap contains too many colors, this determines whether it will dither the output
 * @param threshold the analysis threshold to use if there are too many colors (min 0, practical max is over 100000)
 * @throws IOException if file writing fails for any reason
 */
public void writePrecisely (FileHandle file, Pixmap pixmap, boolean ditherFallback, int threshold) throws IOException {
    OutputStream output = file.write(false);
    try {
        writePrecisely(output, pixmap, ditherFallback, threshold);
    } finally {
        StreamUtils.closeQuietly(output);
    }
}
 
Example 18
Source File: PNG8.java    From gdx-texture-packer-gui with Apache License 2.0 3 votes vote down vote up
/**
 * Writes the pixmap to the stream without closing the stream, optionally computing an 8-bit palette from the given
 * Pixmap. If {@link #palette} is null (the default unless it has been assigned a PaletteReducer value), this will
 * compute a palette from the given Pixmap regardless of computePalette. Optionally dithers the result if
 * {@code dither} is true.
 * @param file a FileHandle that must be writable, and will have the given Pixmap written as a PNG-8 image
 * @param pixmap a Pixmap to write to the given output stream
 * @param computePalette if true, this will analyze the Pixmap and use the most common colors
 * @param dither true if this should dither colors that can't be represented exactly
 * @throws IOException if file writing fails for any reason
 */
public void write (FileHandle file, Pixmap pixmap, boolean computePalette, boolean dither) throws IOException {
    OutputStream output = file.write(false);
    try {
        write(output, pixmap, computePalette, dither);
    } finally {
        StreamUtils.closeQuietly(output);
    }
}
 
Example 19
Source File: PNG8.java    From gdx-texture-packer-gui with Apache License 2.0 3 votes vote down vote up
/**
 * Writes the given Pixmap to the requested FileHandle, optionally computing an 8-bit palette from the most common
 * colors in pixmap. When computePalette is true, if there are 256 or less colors and none are transparent, this
 * will use 256 colors in its palette exactly with no transparent entry, but if there are more than 256 colors or
 * any are transparent, then one color will be used for "fully transparent" and 255 opaque colors will be used. When
 * computePalette is false, this uses the last palette this had computed, or a 253-color bold palette with one
 * fully-transparent color if no palette had been computed yet.
 * @param file a FileHandle that must be writable, and will have the given Pixmap written as a PNG-8 image
 * @param pixmap a Pixmap to write to the given file
 * @param computePalette if true, this will analyze the Pixmap and use the most common colors
 * @throws IOException if file writing fails for any reason
 */
public void write (FileHandle file, Pixmap pixmap, boolean computePalette) throws IOException {
    OutputStream output = file.write(false);
    try {
        write(output, pixmap, computePalette);
    } finally {
        StreamUtils.closeQuietly(output);
    }
}
 
Example 20
Source File: PCM.java    From beatoraja with GNU General Public License v3.0 3 votes vote down vote up
WavInputStream(InputStream p) {
	super(p);
	try {
		if (read() != 'R' || read() != 'I' || read() != 'F' || read() != 'F')
			throw new RuntimeException("RIFF header not found: " + p.toString());

		skipFully(4);

		if (read() != 'W' || read() != 'A' || read() != 'V' || read() != 'E')
			throw new RuntimeException("Invalid wave file header: " + p.toString());

		int fmtChunkLength = seekToChunk('f', 'm', 't', ' ');

		type = read() & 0xff | (read() & 0xff) << 8;

		channels = read() & 0xff | (read() & 0xff) << 8;

		sampleRate = read() & 0xff | (read() & 0xff) << 8 | (read() & 0xff) << 16 | (read() & 0xff) << 24;

		skipFully(6);

		bitsPerSample = read() & 0xff | (read() & 0xff) << 8;

		skipFully(fmtChunkLength - 16);

		dataRemaining = seekToChunk('d', 'a', 't', 'a');
	} catch (Throwable ex) {
		StreamUtils.closeQuietly(this);
		throw new RuntimeException("Error reading WAV file: " + p.toString(), ex);
	}
}