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

The following examples show how to use com.badlogic.gdx.files.FileHandle#file() . 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: Utils.java    From skin-composer with MIT License 6 votes vote down vote up
public static boolean doesImageFitBox(FileHandle fileHandle, float width, float height) {
    boolean result = false;
    String suffix = fileHandle.extension();
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageReader reader = iter.next();
        try (var stream = new FileImageInputStream(fileHandle.file())) {
            reader.setInput(stream);
            int imageWidth = reader.getWidth(reader.getMinIndex());
            int imageHeight = reader.getHeight(reader.getMinIndex());
            result = imageWidth < width && imageHeight < height;
        } catch (IOException e) {
            Gdx.app.error(Utils.class.getName(), "error checking image dimensions", e);
        } finally {
            reader.dispose();
        }
    } else {
        Gdx.app.error(Utils.class.getName(), "No reader available to check image dimensions");
    }
    return result;
}
 
Example 2
Source File: ModInputStream.java    From Cubes with MIT License 6 votes vote down vote up
public ZipModInputStream(FileHandle file) {
  try {
    inputStream = new FileInputStream(file.file());
    zipInputStream = new ZipInputStream(inputStream);
    fileStream = new FilterInputStream(zipInputStream) {
      @Override
      public void close() throws IOException {
        // no close
      }
    };
  } catch (Exception e) {
    try {
      close();
    } catch (IOException ignored) {
    }
    throw new CubesException("Failed to create zip mod input stream", e);
  }
}
 
Example 3
Source File: FileUtils.java    From vis-ui with Apache License 2.0 6 votes vote down vote up
/** Shows given directory in system explorer window. */
@SuppressWarnings("unchecked")
public static void showDirInExplorer (FileHandle dir) throws IOException {
	File dirToShow;
	if (dir.isDirectory()) {
		dirToShow = dir.file();
	} else {
		dirToShow = dir.parent().file();
	}

	if (OsUtils.isMac()) {
		FileManager.revealInFinder(dirToShow);
	} else {
		try {
			// Using reflection to avoid importing AWT desktop which would trigger Android Lint errors
			// This is desktop only, rarely called, performance drop is negligible
			// Basically 'Desktop.getDesktop().open(dirToShow);'
			Class desktopClass = Class.forName("java.awt.Desktop");
			Object desktop = desktopClass.getMethod("getDesktop").invoke(null);
			desktopClass.getMethod("open", File.class).invoke(desktop, dirToShow);
		} catch (Exception e) {
			Gdx.app.log("VisUI", "Can't open file " + dirToShow.getPath(), e);
		}
	}
}
 
Example 4
Source File: FileUtils.java    From gdx-texture-packer-gui with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: FileUtils.java    From gdx-texture-packer-gui with Apache License 2.0 6 votes vote down vote up
/** 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);
        }
    }
 
Example 6
Source File: KtxFileTypeProcessor.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
@Override
public void saveToFile(TexturePacker.Settings settings, BufferedImage image, File file) throws IOException {
    FileHandle tmpPngFile = new FileHandle(File.createTempFile(file.getName(), null));
    FileHandle output = new FileHandle(file);

    super.saveToFile(settings, image, tmpPngFile.file());

    KtxEtc1Processor.process(tmpPngFile, output, alphaChannel);
    tmpPngFile.delete();

    if (zipping) {
        FileUtils.packGzip(output);
    }
}
 
Example 7
Source File: KtxFileTypeProcessor.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
@Override
public void saveToFile(TexturePacker.Settings settings, BufferedImage image, File file) throws IOException {
    FileHandle tmpPngFile = new FileHandle(File.createTempFile(file.getName(), null));
    FileHandle output = new FileHandle(file);

    super.saveToFile(settings, image, tmpPngFile.file());

    KtxEtc2Processor.process(tmpPngFile, output, pixelFormat);
    tmpPngFile.delete();

    if (zipping) {
        FileUtils.packGzip(output);
    }
}
 
Example 8
Source File: PackingProcessor.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
private static BufferedImage createBufferedImage (FileHandle fileHandle) {
    File file = fileHandle.file();
    BufferedImage image;
    try {
        image = ImageIO.read(file);
    } catch (IOException ex) {
        throw new RuntimeException("Error reading image: " + file, ex);
    }
    if (image == null) throw new RuntimeException("Unable to read image: " + file);

    return image;
}
 
Example 9
Source File: GlobalActions.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
@LmlAction("restartApplication") public void restartApplication() {
    FileHandle projectFile = modelService.getProject().getProjectFile();
    if (projectFile != null && projectFile.exists()) {
        App.inst().getParams().startupProject = projectFile.file();
    }
    Gdx.app.postRunnable(new Runnable() {
        @Override
        public void run() {
            App.inst().restart();
        }
    });
}
 
Example 10
Source File: SimplifiedBeatmapLoader.java    From SIFTrain with MIT License 5 votes vote down vote up
private Long computeCRC(FileHandle handle) throws IOException {
    File file = handle.file();
    FileInputStream fis = new FileInputStream(file);
    byte[] bytes = new byte[BLOCK_SIZE];
    CRC32 crc32 = new CRC32();
    int len = fis.read(bytes, 0, BLOCK_SIZE);
    while (len != -1) {
        crc32.update(bytes, 0, len);
        len = fis.read(bytes, 0, BLOCK_SIZE);
    }
    return crc32.getValue();
}
 
Example 11
Source File: AnnotatedJson.java    From libgdx-snippets with MIT License 5 votes vote down vote up
public static <T> void write(FileHandle path, boolean compact, T object, Json json) throws IOException {

		String output = json.toJson(object);
		String prettyOutput = compact ? output : json.prettyPrint(output);

		try (FileOutputStream fos = new FileOutputStream(path.file(), false)) {
			try (Writer writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
				writer.write(prettyOutput);
				writer.flush();
			}
		}
	}
 
Example 12
Source File: AnnotatedJson.java    From libgdx-snippets with MIT License 5 votes vote down vote up
public static <T> void writeGZip(FileHandle path, boolean compact, T object, Json json) throws IOException {

		String output = json.toJson(object);
		String prettyOutput = compact ? output : json.prettyPrint(output);

		try (OutputStream gzip = new GZIPOutputStream(new FileOutputStream(path.file(), false), true)) {
			try (Writer writer = new OutputStreamWriter(gzip, StandardCharsets.UTF_8)) {
				writer.write(prettyOutput);
				writer.flush();
			}
		}
	}
 
Example 13
Source File: FormValidator.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
/**
 * Validates if relative path entered in text field points to an existing file.
 * @param relativeTo path of this file is used to create absolute path from entered in field (see {@link FileExistsValidator}).
 */
public FormInputValidator fileExists (VisValidatableTextField field, FileHandle relativeTo, String errorMsg) {
	FileExistsValidator validator = new FileExistsValidator(relativeTo.file(), errorMsg);
	field.addValidator(validator);
	add(field);
	return validator;

}
 
Example 14
Source File: FormValidator.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
/**
 * Validates if relative path entered in text field points to an non existing file.
 * @param relativeTo path of this file is used to create absolute path from entered in field (see {@link FileExistsValidator}).
 */
public FormInputValidator fileNotExists (VisValidatableTextField field, FileHandle relativeTo, String errorMsg) {
	FileExistsValidator validator = new FileExistsValidator(relativeTo.file(), errorMsg, true);
	field.addValidator(validator);
	add(field);
	return validator;
}
 
Example 15
Source File: Utils.java    From skin-composer with MIT License 5 votes vote down vote up
public static void openFileExplorer(FileHandle startDirectory) throws IOException {
    if (startDirectory.exists()) {
        File file = startDirectory.file();
        Desktop desktop = Desktop.getDesktop();
        desktop.open(file);
    } else {
        throw new IOException("Directory doesn't exist: " + startDirectory.path());
    }
}
 
Example 16
Source File: SimplifiedBeatmapLoader.java    From SIFTrain with MIT License 4 votes vote down vote up
private void convertOsuBeatmap(AssetManager manager, String fileName, FileHandle file, BeatmapParameter parameter) {
    try {
        Gdx.app.log("OSU_LOADER", "converting map: " + fileName);
        FileHandle handle = resolve(fileName);

        Long crc = computeCRC(handle);

        FileHandle[] files;
        // if the osu file was in the root 'beatmaps' directory, go down to the datafiles directory
        if (handle.parent().name().equals("beatmaps")) {
            files = handle.parent().child("datafiles").list(".rs");
        }
        // if the osz file was in the datafiles directory
        else {
            files = handle.parent().list(".rs");
        }
        boolean found = false;
        for (FileHandle fh : files) {
            if (fh.name().equals(handle.name().replace(".osu", ".rs"))) {
                Gdx.app.log("OSU_LOADER", "Map [" + handle.nameWithoutExtension() + ".rs] already exists, checking crc.");
                SongFileInfo info = new Gson().fromJson(fh.readString(), SongFileInfo.class);
                if (info.getCrc() != null && info.getCrc().equals(crc)) {
                    found = true;
                }
                break;
            }
        }
        // don't store files which were already converted.
        // if someone wants a hard reload, they can remove the .rs file
        // and have the game re-generate them
        if (found) {
            Gdx.app.log("OSU_LOADER", "Map [" + handle.nameWithoutExtension() + ".rs] crc match, skipping.");
            return;
        } else {
            Gdx.app.log("OSU_LOADER", "Map [" + handle.nameWithoutExtension() + ".rs] crc didn't match - generating map.");
        }

        InputStream is = new FileInputStream(handle.file());
        SimpleSong beatmap = processOsuStandardFile(is);
        beatmap.setCrc(crc);
        storeBeatmap(beatmap, "beatmaps/datafiles/" + fileName.split("\\\\|/", 2)[1].replace(".osu", ".rs"));
    } catch (Exception e) {
        // something happened while loading the file
        // just exit
        Gdx.app.log("OSZ_LOADER", "Attempted to load a non-mania map: " + fileName);
    }
}
 
Example 17
Source File: ClassFinder.java    From libgdx-snippets with MIT License 2 votes vote down vote up
/**
 * Iterates classes of all URLs filtered by a previous call of {@link ClassFinder#filterURLforClass(Class)}.
 */
public ClassFinder process(Predicate<String> filter, Consumer<Class<?>> processor) {

	for (URL url : urls) {

		Path path;

		// required for Windows paths with spaces
		try {
			path = Paths.get(url.toURI());
		} catch (URISyntaxException e) {
			throw new GdxRuntimeException(e);
		}

		FileHandle file = new FileHandle(path.toFile());

		if (file.isDirectory()) {

			processDirectory(file, file, filter, processor);

		} else if (file.extension().equals("jar")) {

			try (JarFile jar = new JarFile(file.file())) {

				Enumeration<JarEntry> entries = jar.entries();

				while (entries.hasMoreElements()) {

					JarEntry entry = entries.nextElement();

					if (entry.isDirectory()) {
						continue;
					}

					FileHandle entryFile = new FileHandle(entry.getName());

					process(null, entryFile, filter, processor);
				}

			} catch (IOException ignored) {

			}
		}

	}

	return this;
}