Java Code Examples for com.badlogic.gdx.files.FileHandle#write()

The following examples show how to use com.badlogic.gdx.files.FileHandle#write() . 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: LocalCloudSave.java    From dice-heroes with GNU General Public License v3.0 6 votes vote down vote up
@Override public void sync(UserData userData, IConflictResolver resolver) {
    FileHandle dir = Gdx.files.external(DIR);
    dir.mkdirs();
    final FileHandle saveFile = dir.child(SAVE_FILE_NAME);
    final FileHandle conflicted = dir.child(CONFLICT_FILE_NAME);
    if (saveFile.exists()) {
        DiceHeroes app = (DiceHeroes) Gdx.app.getApplicationListener();
        if (app.firstSession) {
            if (!conflicted.exists())
                conflicted.write(saveFile.read(), false);
        }
    }
    toFile(userData, saveFile);
    if (conflicted.exists()) {
        final Map local = fromFile(saveFile);
        final Map server = fromFile(conflicted);
        resolver.resolveConflict(server, new IConflictResolverCallback() {
            @Override public void onResolved(boolean useLocal) {
                conflicted.delete();
                toFile(useLocal ? local : server, saveFile);
            }
        });
    }
}
 
Example 2
Source File: Utils.java    From skin-composer with MIT License 5 votes vote down vote up
/**
 * Extracts a zip entry (file entry)
 * @param zipIn
 * @param filePath
 * @throws IOException
 */
private static void extractFile(ZipInputStream zipIn, FileHandle filePath) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(filePath.write(false));
    byte[] bytesIn = new byte[BUFFER_SIZE];
    int read = 0;
    while ((read = zipIn.read(bytesIn)) != -1) {
        bos.write(bytesIn, 0, read);
    }
    bos.close();
}
 
Example 3
Source File: BinGenerationTool.java    From riiablo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void generate(FileHandle txt, FileHandle bin, Class<Excel> excelClass) throws Exception {
  Gdx.app.log(TAG, bin.toString());
  Excel<Excel.Entry> excel = Excel.load(excelClass, txt, Excel.EXPANSION);
  OutputStream out = null;
  try {
    out = bin.write(false, 8192);
    LittleEndianDataOutputStream dos = new LittleEndianDataOutputStream(out);
    excel.writeBin(dos);
  } catch (Throwable t) {
    Gdx.app.error(TAG, t.getMessage(), t);
  } finally {
    IOUtils.closeQuietly(out);
  }

  if (VALIDATE_BIN) {
    Class<Excel.Entry> entryClass = getEntryClass(excelClass);
    String binClassName = excelClass.getName() + "Bin";
    Class binClass = Class.forName(binClassName);
    Method equals = binClass.getMethod("equals", entryClass, entryClass);
    Excel binExcel = Excel.load(excelClass, txt, bin, null);
    if (binExcel.size() != excel.size()) Gdx.app.error(TAG, "excel sizes do not match!");
    for (Excel.Entry e1 : excel) {
      Excel.Entry eq = getEqual(equals, e1, binExcel);
      if (eq == null) {
        Gdx.app.log(TAG, "ERROR at index " + e1);
        //break;
      } else {
        //Gdx.app.log(TAG, e1 + "=" + eq);
      }
    }
  }
}
 
Example 4
Source File: SaveAreaIO.java    From Cubes with MIT License 5 votes vote down vote up
public static boolean write(Save save, Area area) {
  if (save.readOnly) return false;
  if (!area.isReady()) return false;

  AreaMap map = area.areaMap();
  DataGroup[] dataGroups;
  if (map == null || map.world == null || map.world.entities == null) {
    dataGroups = new DataGroup[0];
  } else {
    dataGroups = map.world.entities.getEntitiesForSave(area.areaX, area.areaZ);
  }
  if (!area.modifiedSinceSave(dataGroups)) return false;
  area.saveModCount();

  Deflater deflater = deflaterThreadLocal.get();

  FileHandle file = file(save, area.areaX, area.areaZ);
  try {
    deflater.reset();
    OutputStream stream = file.write(false, 8192);
    DeflaterOutputStream deflaterStream = new DeflaterOutputStream(stream, deflater);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(deflaterStream);
    DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
    area.writeSave(dataOutputStream, dataGroups);
    bufferedOutputStream.flush();
    deflaterStream.finish();
    stream.close();
  } catch (Exception e) {
    Log.error("Failed to write area " + area.areaX + "," + area.areaZ, e);
    return false;
  }

  return true;
}
 
Example 5
Source File: Save.java    From Cubes with MIT License 5 votes vote down vote up
public void writeCave(AreaReference areaReference, Cave cave) {
  if (readOnly) return;

  FileHandle folder = folderCave();
  FileHandle file = folder.child(areaReference.areaX + "_" + areaReference.areaZ);
  try {
    OutputStream write = file.write(false);
    DataOutputStream dataOutputStream = new DataOutputStream(write);
    cave.write(dataOutputStream);
    write.close();
  } catch (IOException e) {
    Log.warning("Failed to write cave", e);
  }
}
 
Example 6
Source File: GdxAssetCache.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static FileHandle getFileHandle(String path) {
    FileHandle fileHandle = Gdx.files.local("gdxtemp/"+path);
    if (!fileHandle.exists()) {
        InputStream is = GdxAssetCache.class.getClassLoader().getResourceAsStream(path);
        fileHandle.write(is, false);
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return fileHandle;
}
 
Example 7
Source File: Replay.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
/** Saves its data to a filename named as its replay ID in the replays output directory for this data's trackId and userId */
public boolean save () {
	if (isValid()) { // sanity check
		String dest = ReplayUtils.getDestinationDir(info);

		// ensure destination directory exists
		Gdx.files.external(dest).mkdirs();

		FileHandle hf = Gdx.files.external(ReplayUtils.getFullPath(info));
		if (hf.exists()) {
			throw new URacerRuntimeException("Replay " + info.getShortId() + " exists, this should never happens! ("
				+ info.replayId + ")");
		}

		try {
			GZIPOutputStream gzos = new GZIPOutputStream(hf.write(false));
			DataOutputStream os = new DataOutputStream(gzos);

			// replay info data
			os.writeUTF(info.replayId);
			os.writeUTF(info.userId);
			os.writeUTF(info.trackId);
			os.writeInt(info.trackTimeTicks);
			os.writeInt(info.eventsCount);
			os.writeLong(info.created);

			// car data
			os.writeFloat(carPositionMt.x);
			os.writeFloat(carPositionMt.y);
			os.writeFloat(carOrientationRads);

			// write the effective number of captured CarForces events
			for (int i = 0; i < info.eventsCount; i++) {
				CarForces f = forces[i];
				os.writeFloat(f.velocity_x);
				os.writeFloat(f.velocity_y);
				os.writeFloat(f.angularVelocity);
			}

			os.close();

			return true;
		} catch (Exception e) {
			Gdx.app.log("Replay", "Couldn't save replay, reason: " + e.getMessage());
			return false;
		}
	} else {
		Gdx.app.log("Replay", "Couldn't save replay because its not valid.");
		return false;
	}
}
 
Example 8
Source File: Game.java    From shattered-pixel-dungeon-gdx with GNU General Public License v3.0 4 votes vote down vote up
public OutputStream openFileOutput(String fileName) {
	final FileHandle fh = Gdx.files.external(basePath != null ? basePath + fileName : fileName);
	return fh.write(false);
}
 
Example 9
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 10
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 11
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. Uses the given threshold while analyzing
 * the palette if this needs to compute a palette; threshold values can be as low as 0 to try to use as many colors
 * as possible (prefer {@link  #writePrecisely(FileHandle, Pixmap, boolean, int)} for that, though) and can range up
 * to very high numbers if very few colors should be used; usually threshold is from 100 to 800. 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
 * @param threshold the analysis threshold to use if computePalette is true (min 0, practical max is over 100000)
 * @throws IOException if file writing fails for any reason
 */
public void write (FileHandle file, Pixmap pixmap, boolean computePalette, boolean dither, int threshold) throws IOException {
    OutputStream output = file.write(false);
    try {
        write(output, pixmap, computePalette, dither, threshold);
    } finally {
        StreamUtils.closeQuietly(output);
    }
}
 
Example 12
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);
    }
}