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

The following examples show how to use com.badlogic.gdx.files.FileHandle#exists() . 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: ProjectData.java    From skin-composer with MIT License 6 votes vote down vote up
public Array<RecentFile> getRecentFiles() {
    Array<RecentFile> returnValue = new Array<>();
    int maxIndex = Math.min(MAX_RECENT_FILES, generalPref.getInteger("recentFilesCount", 0));
    for (int i = 0; i < maxIndex; i++) {
        String path = generalPref.getString("recentFile" + i);
        FileHandle file = new FileHandle(path);
        RecentFile recentFile = new RecentFile();
        recentFile.fileHandle = file;
        recentFile.name = file.nameWithoutExtension();
        if (file.exists()) {
            returnValue.add(recentFile);
        }
    }
    
    return returnValue;
}
 
Example 2
Source File: ReplayUtils.java    From uracer-kotd with Apache License 2.0 6 votes vote down vote up
public static boolean pruneReplay (ReplayInfo info) {
	if (info != null && ReplayUtils.areValidIds(info)) {
		String rid = info.getId();
		if (rid.length() > 0) {
			String path = getFullPath(info);
			if (path.length() > 0) {
				FileHandle hf = Gdx.files.external(path);
				if (hf.exists()) {
					hf.delete();
					Gdx.app.log("ReplayUtils", "Pruned #" + rid);
					return true;
				} else {
					Gdx.app.error("ReplayUtils", "Couldn't prune #" + rid);
				}
			}
		}
	}

	return false;
}
 
Example 3
Source File: Entry.java    From ingress-apk-mod with Apache License 2.0 6 votes vote down vote up
public static FileHandle AssetFinder_onGetAssetPath(String in) {
    if (!in.startsWith("{data:")) {
        return null;
    }
    int pos1 = in.indexOf("/data/", 6);
    int pos2 = in.indexOf(",", pos1 + 6);
    String pre = in.substring(6, pos1) + "/";
    String post = "/" + in.substring(pos1 + 6, pos2);

    UiVariant variant = Mod.currUiVariant;
    while (variant != null) {
        FileHandle file = Gdx.files.internal(pre + variant.name + post);
        if (file.exists()) {
            return file;
        }
        variant = UiVariant.byName.get(variant.parent);
    }
    return null;
}
 
Example 4
Source File: TalosAssetProvider.java    From talos with Apache License 2.0 6 votes vote down vote up
private Sprite findSpriteOrLoad (String assetName) {
	final Sprite region = atlas.createSprite(assetName);
	if (region == null) {
		//Look in all paths, and hopefully load the requested asset, or fail (crash)
		//if has extension remove it
		if(assetName.contains(".")) {
			assetName = assetName.substring(0, assetName.lastIndexOf("."));
		}
		FileHandle file = findFile(assetName);
		if (file == null || !file.exists()) {
			//throw new GdxRuntimeException("No region found for: " + assetName + " from provider");
			// try the tracker first
			file = TalosMain.Instance().FileTracker().findFileByName(assetName + ".png");
			if(file == null) {
				return null;
			}
		}
		Texture texture = new Texture(file);
		Sprite textureRegion = new Sprite(texture);
		atlas.addRegion(assetName, textureRegion);
		return textureRegion;
	}
	return region;
}
 
Example 5
Source File: UserDataHelper.java    From dice-heroes with GNU General Public License v3.0 6 votes vote down vote up
private void loadKey() {
    if (key != null)
        return;
    FileHandle keyFile = Gdx.files.local("app.key");
    if (!keyFile.exists()) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            key = keyGenerator.generateKey().getEncoded();
            keyFile.writeBytes(key, false);
        } catch (Exception e) {
            Logger.log("failed to load key", e);
        }
    } else {
        key = keyFile.readBytes();
    }
}
 
Example 6
Source File: ConfigurationController.java    From gdx-texture-packer-gui with Apache License 2.0 6 votes vote down vote up
@Initiate(priority = -1000)
public void setupInitialProject(ModelService modelService, ProjectSerializer projectSerializer) {
    AppParams params = App.inst().getParams();
    if (params.startupProject == null) return;

    FileHandle projectFile = FileUtils.toFileHandle(params.startupProject);
    if (!projectFile.exists()) {
        Gdx.app.error(TAG, "Project file: " + projectFile + " doesn't exists.");
        return;
    }

    ProjectModel project = projectSerializer.loadProject(projectFile);
    project.setProjectFile(projectFile);

    modelService.setProject(project);
}
 
Example 7
Source File: AndroidModLoader.java    From Cubes with MIT License 6 votes vote down vote up
private FileHandle convertToDex(FileHandle fileHandle) throws Exception {
  String inputHash = hashFile(fileHandle);
  
  FileHandle cacheDir = new FileHandle(androidCompatibility.androidLauncher.getCacheDir());
  FileHandle dexDir = cacheDir.child("converted_mod_dex");
  dexDir.mkdirs();
  FileHandle dexFile = dexDir.child(inputHash + ".dex");
  
  if (!dexFile.exists()) {
    Log.warning("Trying to convert jar to dex: " + fileHandle.file().getAbsolutePath());
    com.android.dx.command.dexer.Main.Arguments arguments = new com.android.dx.command.dexer.Main.Arguments();
    arguments.parse(new String[]{"--output=" + dexFile.file().getAbsolutePath(), fileHandle.file().getAbsolutePath()});
    int result = com.android.dx.command.dexer.Main.run(arguments);
    if (result != 0) throw new CubesException("Failed to convert jar to dex [" + result + "]: " + fileHandle.file().getAbsolutePath());
    Log.warning("Converted jar to dex: " + fileHandle.file().getAbsolutePath());
  }
  
  return dexFile;
}
 
Example 8
Source File: WelcomeScreen.java    From gdx-skineditor with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param projectName
 */
public void createProject(String projectName) {

	FileHandle projectFolder = Gdx.files.local("projects").child(projectName);
	if (projectFolder.exists() == true) {
		game.showNotice("Error", "Project name already in use!", stage);
		return;
	}

	projectFolder.mkdirs();
	projectFolder.child("assets").mkdirs();
	projectFolder.child("backups").mkdirs();
	game.skin.save(projectFolder.child("uiskin.json"));

	// Copy assets
	FileHandle assetsFolder = Gdx.files.local("resources/raw");
	assetsFolder.copyTo(projectFolder.child("assets"));
	// Rebuild from raw resources
	TexturePacker.Settings settings = new TexturePacker.Settings();
	settings.combineSubdirectories = true;
	TexturePacker.process(settings, "projects/" + projectName +"/assets/", "projects/" + projectName, "uiskin");

	game.showNotice("Operation completed", "New project successfully created.", stage);
	
	refreshProjects();
}
 
Example 9
Source File: GlobalActions.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
@LmlAction("editCustomHotkeys") void editCustomHotkeys() {
    FileHandle userHotkeyFile = Gdx.files.external(AppConstants.EXTERNAL_DIR + "/hotkeys_user.txt");
    if (!userHotkeyFile.exists()) {
        Gdx.files.internal("hotkeys_user.txt").copyTo(userHotkeyFile);
    }
    try {
        Desktop.getDesktop().open(userHotkeyFile.file());
    } catch (IOException e) {
        Gdx.app.error(TAG, "Error opening " + userHotkeyFile, e);
    }
}
 
Example 10
Source File: FormValidator.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean validate (String input) {
	FileHandle file = Gdx.files.absolute(input);
	if (file.exists() == false || file.isDirectory() == false) return false;
	if (mustBeEmpty) {
		return file.list().length == 0;
	} else {
		return file.list().length != 0;
	}
}
 
Example 11
Source File: InputFile.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
public InputFile(FileHandle fileHandle, Type type) {
    this.fileHandle = fileHandle;
    this.type = type;

    // Determine if the file is a directory.
    // We cannot use just `fileHandle.isDirectory()`,
    // because in case the file doesn't exist it always returns `false`.
    if (fileHandle.exists()) {
        this.directory = fileHandle.isDirectory();
    } else {
        this.directory = fileHandle.extension().length() == 0;
    }
}
 
Example 12
Source File: WindowParamsPersistingApplicationWrapper.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
private void loadWindowParams(LwjglApplicationConfiguration configuration) {
    FileHandle file = new FileHandle(LwjglFiles.externalPath + configuration.preferencesDirectory + "/window_params.xml");
    if (!file.exists()) return;

    DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode();
    int screenWidth = displayMode.getWidth();
    int screenHeight = displayMode.getHeight();

    Preferences prefs = new LwjglPreferences(file);
    configuration.width = MathUtils.clamp(prefs.getInteger("width", configuration.width), 320, screenWidth);
    configuration.height = MathUtils.clamp(prefs.getInteger("height", configuration.height), 320, screenHeight);
    configuration.x = MathUtils.clamp(prefs.getInteger("x", configuration.x), 0, screenWidth - configuration.width);
    configuration.y = MathUtils.clamp(prefs.getInteger("y", configuration.y), 0, screenHeight - configuration.height);
}
 
Example 13
Source File: PolylineModuleWrapper.java    From talos with Apache License 2.0 5 votes vote down vote up
public void setTexture(String path) {
    FileHandle fileHandle = tryAndFineTexture(path);
    if(fileHandle.exists()) {
        TextureRegion region = new TextureRegion(new Texture(fileHandle));
        module.setRegion(fileHandle.nameWithoutExtension(), region);
        dropWidget.setDrawable(new TextureRegionDrawable(region));
    }
    filePath = fileHandle.path();
    regionName = fileHandle.nameWithoutExtension();
}
 
Example 14
Source File: GLTFDemo.java    From gdx-gltf with Apache License 2.0 5 votes vote down vote up
protected void setImage(ModelEntry entry) {
	if(entry.screenshot != null){
		if(entry.url != null){
			HttpRequest httpRequest = new HttpRequest(HttpMethods.GET);
			httpRequest.setUrl(entry.url + entry.screenshot);

			Gdx.net.sendHttpRequest(httpRequest, new SafeHttpResponseListener(){
				@Override
				protected void handleData(byte[] bytes) {
					Pixmap pixmap = PixmapBinaryLoaderHack.load(bytes, 0, bytes.length);
					ui.setImage(new Texture(pixmap));
					pixmap.dispose();
				}
				@Override
				protected void handleError(Throwable t) {
					Gdx.app.error(TAG, "request error", t);
				}
				@Override
				protected void handleEnd() {
				}
			});
		}else{
			FileHandle file = rootFolder.child(entry.name).child(entry.screenshot);
			if(file.exists()){
				ui.setImage(new Texture(file));
			}else{
				Gdx.app.error("DEMO UI", "file not found " + file.path());
			}
		}
	}
}
 
Example 15
Source File: AssetManager.java    From Mundus with Apache License 2.0 5 votes vote down vote up
/**
 * Loads an asset, given it's meta file.
 *
 * @param meta
 *            meta file of asset
 * @return asset or null
 * @throws AssetNotFoundException
 *             if a meta file points to a non existing asset
 * @throws MetaFileParseException
 *             if a meta file can't be parsed
 */
public Asset loadAsset(Meta meta) throws MetaFileParseException, AssetNotFoundException {
    // get handle to asset
 //   String assetPath = meta.getFile().pathWithoutExtension();
    FileHandle assetFile = meta.getFile().sibling(meta.getFile().nameWithoutExtension());

    // check if asset exists
    if (!assetFile.exists()) {
        throw new AssetNotFoundException("Meta file found, but asset does not exist: " + meta.getFile().path());
    }

    // load actual asset
    Asset asset = null;
    switch (meta.getType()) {
    case TEXTURE:
        asset = loadTextureAsset(meta, assetFile);
        break;
    case PIXMAP_TEXTURE:
        asset = loadPixmapTextureAsset(meta, assetFile);
        break;
    case TERRAIN:
        asset = loadTerrainAsset(meta, assetFile);
        break;
    case MODEL:
        asset = loadModelAsset(meta, assetFile);
        break;
    case MATERIAL:
        asset = loadMaterialAsset(meta, assetFile);
        break;
    default:
        return null;
    }

    addAsset(asset);
    return asset;
}
 
Example 16
Source File: FileTracker.java    From talos with Apache License 2.0 5 votes vote down vote up
public FileHandle findFileByName(String name) {
    final FileTab currentTab = TalosMain.Instance().ProjectController().currentTab;
    for(FileHandle handle: tabMaps.get(currentTab).keys()) {
        if(handle.name().equals(name) || handle.nameWithoutExtension().equals(name)) {
            if(handle.exists()) return handle;
        }
    }

    return null;
}
 
Example 17
Source File: FileHistoryManager.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
private boolean setDirectoryFromHistory (FileHandle dir) {
	if (dir.exists()) {
		callback.setDirectory(dir, HistoryPolicy.IGNORE);
		return true;
	} else {
		Dialogs.showErrorDialog(callback.getStage(), DIRECTORY_NO_LONGER_EXISTS.get());
		return false;
	}
}
 
Example 18
Source File: FileUtils.java    From shattered-pixel-dungeon with GNU General Public License v3.0 4 votes vote down vote up
public static boolean fileExists( String name ){
	FileHandle file = getFileHandle( name );
	return file.exists() && !file.isDirectory();
}
 
Example 19
Source File: Replay.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
public static Replay load (String fullpathFilename) {
	FileHandle fh = Gdx.files.external(fullpathFilename);
	if (fh.exists()) {
		try {
			GZIPInputStream gzis = new GZIPInputStream(fh.read());
			DataInputStream is = new DataInputStream(gzis);

			Replay r = new Replay();
			r.info.completed = true;

			// replay info data
			r.info.replayId = is.readUTF();
			r.info.userId = is.readUTF();
			r.info.trackId = is.readUTF();
			r.info.trackTimeTicks = is.readInt();
			r.info.eventsCount = is.readInt();
			r.info.created = is.readLong();

			// car data
			r.carPositionMt.x = is.readFloat();
			r.carPositionMt.y = is.readFloat();
			r.carOrientationRads = is.readFloat();

			for (int i = 0; i < r.info.eventsCount; i++) {
				r.forces[i].velocity_x = is.readFloat();
				r.forces[i].velocity_y = is.readFloat();
				r.forces[i].angularVelocity = is.readFloat();
			}

			is.close();

			return r;
		} catch (Exception e) {
			Gdx.app.log("Replay",
				"Couldn't load replay (" + fullpathFilename + "), reason: " + e.getMessage() + " (" + e.toString() + ")");
		}
	} else {
		Gdx.app.log("Replay", "The specified replay doesn't exist (" + fullpathFilename + ")");
	}

	return null;
}
 
Example 20
Source File: GameScreen.java    From Klooni1010 with GNU General Public License v3.0 4 votes vote down vote up
private void deleteSave() {
    final FileHandle handle = Gdx.files.local(SAVE_DAT_FILENAME);
    if (handle.exists())
        handle.delete();
}