/** * Blocking version of {@link #loadGameState(String, ILoadGameStateResponseListener)} * * @param fileId * @return game state data * @throws IOException */ public byte[] loadGameStateSync(String fileId) throws IOException { InputStream stream = null; byte[] data = null; try { File remoteFile = findFileByNameSync(fileId); if (remoteFile != null) { stream = GApiGateway.drive.files().get(remoteFile.getId()).executeMediaAsInputStream(); data = StreamUtils.copyStreamToByteArray(stream); } } finally { StreamUtils.closeQuietly(stream); } return data; }
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); } }
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; int n =inputStream.read(bytesBuffer); while ((bytesRead = n) != -1) { digest.update(bytesBuffer, 0, bytesRead); n=inputStream.read(bytesBuffer); } 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); } }
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); } }
public byte[] getResult () { InputStream input = getInputStream(); // If the response does not contain any content, input will be null. if (input == null) { return StreamUtils.EMPTY_BYTES; } try { return StreamUtils.copyStreamToByteArray(input, connection.getContentLength()); } catch (IOException e) { return StreamUtils.EMPTY_BYTES; } finally { StreamUtils.closeQuietly(input); } }
public String getResultAsString () { InputStream input = getInputStream(); // If the response does not contain any content, input will be null. if (input == null) { return ""; } try { return StreamUtils.copyStreamToString(input, connection.getContentLength()); } catch (IOException e) { return ""; } finally { StreamUtils.closeQuietly(input); } }
public Sound (OpenALAudio 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); } }
@SuppressWarnings("unchecked") @Override public void loadAsync (AssetManager manager, String fileName, FileHandle file, BehaviorTreeParameter parameter) { this.behaviorTree = null; Object blackboard = null; BehaviorTreeParser parser = null; if (parameter != null) { blackboard = parameter.blackboard; parser = parameter.parser; } if (parser == null) parser = new BehaviorTreeParser(); Reader reader = null; try { reader = file.reader(); this.behaviorTree = parser.parse(reader, blackboard); } finally { StreamUtils.closeQuietly(reader); } }
/** 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); } }
public ExperienceTable(FileHandle file) { requiredExpGain = new ObjectMap<Integer, Integer>(); requiredExpTotal = new ObjectMap<Integer, Integer>(); CSVReader reader = new CSVReader(file.reader()); try { String[] line = reader.readNext(); int total = 0; for (int i = 0; i < line.length; ++i) { int currGain = Integer.parseInt(line[i]); requiredExpGain.put(i+2, currGain); total += currGain; requiredExpTotal.put(i+2, total); } } catch (IOException e) { throw new GdxRuntimeException(e); } finally { StreamUtils.closeQuietly(reader); } }
/** Synchronously downloads file by URL*/ public static void downloadFile(FileHandle output, String urlString) throws IOException { // ReadableByteChannel rbc = null; // FileOutputStream fos = null; // try { // URL url = new URL(urlString); // rbc = Channels.newChannel(url.openStream()); // fos = new FileOutputStream(output.file()); // fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); // } finally { // StreamUtils.closeQuietly(rbc); // StreamUtils.closeQuietly(fos); // } InputStream in = null; FileOutputStream out = null; try { URL url = new URL(urlString); in = url.openStream(); out = new FileOutputStream(output.file()); StreamUtils.copyStream(in, out); } finally { StreamUtils.closeQuietly(in); StreamUtils.closeQuietly(out); } }
public static void unpackZip(FileHandle input, FileHandle output) throws IOException { ZipFile zipFile = new ZipFile(input.file()); File outputDir = output.file(); try { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(outputDir, entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { entryDestination.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); StreamUtils.copyStream(in, out); StreamUtils.closeQuietly(in); out.close(); } } } finally { StreamUtils.closeQuietly(zipFile); } }
public ETC1Data (FileHandle pkmFile) { byte[] buffer = new byte[1024 * 10]; DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))); int fileSize = in.readInt(); compressedData = BufferUtils.newUnsafeByteBuffer(fileSize); int readBytes = 0; while ((readBytes = in.read(buffer)) != -1) { compressedData.put(buffer, 0, readBytes); } compressedData.position(0); compressedData.limit(compressedData.capacity()); } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm file '" + pkmFile + "'", e); } finally { StreamUtils.closeQuietly(in); } width = getWidthPKM(compressedData, 0); height = getHeightPKM(compressedData, 0); dataOffset = PKM_HEADER_SIZE; compressedData.position(dataOffset); checkNPOT(); }
public void loadEmitters (FileHandle effectFile) { InputStream input = effectFile.read(); emitters.clear(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(input), 512); while (true) { ParticleEmitter emitter = new ParticleEmitter(reader); emitters.add(emitter); if (reader.readLine() == null) break; if (reader.readLine() == null) break; } } catch (IOException ex) { throw new GdxRuntimeException("Error loading effect: " + effectFile, ex); } finally { StreamUtils.closeQuietly(reader); } }
/** Loads a PolygonRegion from a PSH (Polygon SHape) file. The PSH file format defines the polygon vertices before * triangulation: * <p> * s 200.0, 100.0, ... * <p> * Lines not prefixed with "s" are ignored. PSH files can be created with external tools, eg: <br> * https://code.google.com/p/libgdx-polygoneditor/ <br> * http://www.codeandweb.com/physicseditor/ * @param file file handle to the shape definition file */ public PolygonRegion load (TextureRegion textureRegion, FileHandle file) { BufferedReader reader = file.reader(256); try { while (true) { String line = reader.readLine(); if (line == null) break; if (line.startsWith("s")) { // Read shape. String[] polygonStrings = line.substring(1).trim().split(","); float[] vertices = new float[polygonStrings.length]; for (int i = 0, n = vertices.length; i < n; i++) vertices[i] = Float.parseFloat(polygonStrings[i]); // It would probably be better if PSH stored the vertices and triangles, then we don't have to triangulate here. return new PolygonRegion(textureRegion, vertices, triangulator.computeTriangles(vertices).toArray()); } } } catch (IOException ex) { throw new GdxRuntimeException("Error reading polygon shape file: " + file, ex); } finally { StreamUtils.closeQuietly(reader); } throw new GdxRuntimeException("Polygon shape not found: " + file); }
/** Reads the entire file into a string using the specified charset. * @param charset If null the default charset is used. * @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public String readString (String charset) { StringBuilder output = new StringBuilder(estimateLength()); InputStreamReader reader = null; try { if (charset == null) reader = new InputStreamReader(read()); else reader = new InputStreamReader(read(), charset); char[] buffer = new char[256]; while (true) { int length = reader.read(buffer); if (length == -1) break; output.append(buffer, 0, length); } } catch (IOException ex) { throw new GdxRuntimeException("Error reading layout file: " + this, ex); } finally { StreamUtils.closeQuietly(reader); } return output.toString(); }
/** Reads the entire file into the byte array. The byte array must be big enough to hold the file's data. * @param bytes the array to load the file into * @param offset the offset to start writing bytes * @param size the number of bytes to read, see {@link #length()} * @return the number of read bytes */ public int readBytes (byte[] bytes, int offset, int size) { InputStream input = read(); int position = 0; try { while (true) { int count = input.read(bytes, offset + position, size - position); if (count <= 0) break; position += count; } } catch (IOException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } finally { StreamUtils.closeQuietly(input); } return position - offset; }
/** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be * determined. */ public long length () { if (type == FileType.Classpath || (type == FileType.Internal && !file.exists())) { InputStream input = read(); try { return input.available(); } catch (Exception ignored) { } finally { StreamUtils.closeQuietly(input); } return 0; } return file().length(); }
void saveEffect () { FileDialog dialog = new FileDialog(editor, "Save Effect", FileDialog.SAVE); if (lastDir != null) dialog.setDirectory(lastDir); dialog.setVisible(true); String file = dialog.getFile(); String dir = dialog.getDirectory(); if (dir == null || file == null || file.trim().length() == 0) return; lastDir = dir; int index = 0; for (ParticleEmitter emitter : editor.effect.getEmitters()) emitter.setName((String)emitterTableModel.getValueAt(index++, 0)); File outputFile = new File(dir, file); Writer fileWriter = null; try { fileWriter = new FileWriter(outputFile); editor.effect.save(fileWriter); } catch (Exception ex) { System.out.println("Error saving effect: " + outputFile.getAbsolutePath()); ex.printStackTrace(); JOptionPane.showMessageDialog(editor, "Error saving effect."); } finally { StreamUtils.closeQuietly(fileWriter); } }
public void loadEmitters (FileHandle effectFile) { InputStream input = effectFile.read(); emitters.clear(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(input), 512); while (true) { MyParticleEmitter emitter = new MyParticleEmitter(reader); emitters.add(emitter); if (reader.readLine() == null) break; if (reader.readLine() == null) break; } } catch (IOException ex) { throw new GdxRuntimeException("Error loading effect: " + effectFile, ex); } finally { StreamUtils.closeQuietly(reader); } }
public Sound(OpenALAudio 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); } }
public Sound(OpenALAudio 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); } }
@Override public Actor createActor (Skin skin) { // Create the semaphore NonBlockingSemaphoreRepository.clear(); NonBlockingSemaphoreRepository.addSemaphore("dogSemaphore", 1); Reader reader = null; try { // Parse Buddy's tree reader = Gdx.files.internal("data/dogSemaphore.tree").reader(); BehaviorTreeParser<Dog> parser = new BehaviorTreeParser<Dog>(BehaviorTreeParser.DEBUG_HIGH); BehaviorTree<Dog> buddyTree = parser.parse(reader, new Dog("Buddy")); // Clone Buddy's tree for Snoopy BehaviorTree<Dog> snoopyTree = (BehaviorTree<Dog>)buddyTree.cloneTask(); snoopyTree.setObject(new Dog("Snoopy")); // Create split pane BehaviorTreeViewer<?> buddyTreeViewer = createTreeViewer(buddyTree.getObject().name, buddyTree, false, skin); BehaviorTreeViewer<?> snoopyTreeViewer = createTreeViewer(snoopyTree.getObject().name, snoopyTree, false, skin); return new SplitPane(new ScrollPane(buddyTreeViewer, skin), new ScrollPane(snoopyTreeViewer, skin), true, skin, "default-horizontal"); } finally { StreamUtils.closeQuietly(reader); } }
public String getStringResponse() { ByteArrayInputStream input = new ByteArrayInputStream(responseBytes); try { return StreamUtils.copyStreamToString(input, responseBytes.length); } catch (IOException e) { return ""; } finally { StreamUtils.closeQuietly(input); } }
public Sound (OpenALAudio 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); } }
WavInputStream (FileHandle file) { super(file.read()); try { if (read() != 'R' || read() != 'I' || read() != 'F' || read() != 'F') throw new GdxRuntimeException("RIFF header not found: " + file); skipFully(4); if (read() != 'W' || read() != 'A' || read() != 'V' || read() != 'E') throw new GdxRuntimeException("Invalid wave file header: " + file); int fmtChunkLength = seekToChunk('f', 'm', 't', ' '); int type = read() & 0xff | (read() & 0xff) << 8; if (type != 1) throw new GdxRuntimeException("WAV files must be PCM: " + type); channels = read() & 0xff | (read() & 0xff) << 8; if (channels != 1 && channels != 2) throw new GdxRuntimeException("WAV files must have 1 or 2 channels: " + channels); sampleRate = read() & 0xff | (read() & 0xff) << 8 | (read() & 0xff) << 16 | (read() & 0xff) << 24; skipFully(6); int bitsPerSample = read() & 0xff | (read() & 0xff) << 8; if (bitsPerSample != 16) throw new GdxRuntimeException("WAV files must have 16 bits per sample: " + bitsPerSample); skipFully(fmtChunkLength - 16); dataRemaining = seekToChunk('d', 'a', 't', 'a'); } catch (Throwable ex) { StreamUtils.closeQuietly(this); throw new GdxRuntimeException("Error reading WAV file: " + file, ex); } }
public void write (FileHandle file, Pixmap pixmap) throws IOException { OutputStream output = file.write(false); try { write(output, pixmap); } finally { StreamUtils.closeQuietly(output); } }
/** 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); } }
public static void writeOptions(Files files) { if (configuration == null || configuration.options == null) { return; } String file = FOLDER_USER_DATA + "config.xml"; FileHandle userOptions = files.local(file); OutputStream outputStream = userOptions.write(false); Writer writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); try { writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); XmlWriter xml = new XmlWriter(writer); xml.element("gameOptions"); XMLUtil.writePrimitives(configuration.options, xml, true); xml.element(XML_KEY_BINDINGS); for (KeyBindings binding : KeyBindings.values()) { xml.element(binding.name().toLowerCase(Locale.ENGLISH)); xml.text(binding.getKeys().toString(",")); xml.pop(); } xml.pop(); xml.pop(); xml.flush(); } catch (final IOException e) { throw new GdxRuntimeException("Cannot write configuration file " + file + ", aborting.", e); } finally { StreamUtils.closeQuietly(writer); } }
private static void extractFile (ZipInputStream in, FileHandle outdir, String name) throws IOException { Debug.log("Extract", outdir.path() + "\\" + name); byte[] buffer = new byte[BUFFER_SIZE]; outdir.child(name).delete(); StreamUtils.copyStream(in, outdir.child(name).write(true)); }
@Override public byte[] readBytes () { InputStream input = read(); try { return StreamUtils.copyStreamToByteArray(input, 512); } catch (IOException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } finally { StreamUtils.closeQuietly(input); } }
public JglfwPreferences (FileHandle file) { this.file = file; if (!file.exists()) return; InputStream in = null; try { in = new BufferedInputStream(file.read()); properties.load(in); } catch (Throwable ex) { ex.printStackTrace(); } finally { StreamUtils.closeQuietly(in); } }
public void flush () { OutputStream out = null; try { out = new BufferedOutputStream(file.write(false)); properties.store(out, null); } catch (Exception ex) { throw new GdxRuntimeException("Error writing preferences: " + file, ex); } finally { StreamUtils.closeQuietly(out); } }