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

The following examples show how to use com.badlogic.gdx.files.FileHandle#readString() . 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: VectorField.java    From talos with Apache License 2.0 6 votes vote down vote up
public void setBakedData(FileHandle fileHandle) {
    if(!fileHandle.extension().equals("fga")) {
        // throw exception and return
        return;
    }

    String content = fileHandle.readString();
    String[] arr = content.split(",");
    xSize = Integer.parseInt(arr[0]);
    ySize = Integer.parseInt(arr[1]);
    zSize = Integer.parseInt(arr[2]);

    field = new Vector3[xSize][ySize][zSize];

    int index = 3;

    for(int i = 0; i < xSize; i++) {
        for(int j = 0; j < ySize; j++) {
            for(int k = 0; k < zSize; k++) {
                field[i][j][k] = new Vector3(readParam(arr, index++), readParam(arr, index++), readParam(arr, index++));
            }
        }
    }
}
 
Example 2
Source File: HighScoreManager.java    From FruitCatcher with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void retrieveHighScores() {
	FileHandle highScoresFile = Gdx.files.local(SCORES_DATA_FILE);
	if( highScoresFile.exists() ) {
		Json json = new Json();
		try {
			String encScoresStr = highScoresFile.readString();
			String scoresStr = Base64Coder.decodeString( encScoresStr );
			highScores = json.fromJson(ArrayList.class, HighScore.class, scoresStr);
			return;
           } catch( Exception e ) {
               Gdx.app.error( HighScoreManager.class.getName(), 
               		"Unable to parse high scores data file", e );
           }
	}
	highScores = new ArrayList<HighScore>();
	String playerName = textResources.getDefaultPlayerName();
	for(int i=0;i<HIGH_SCORES_COUNT;i++){
		highScores.add(new HighScore(playerName, 50 - 10*i, false));
	}
}
 
Example 3
Source File: FileLoading.java    From ud406 with MIT License 6 votes vote down vote up
@Override
public void create() {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");

    String encryptedPunchline = encrypt("Very Carefully");
    Gdx.app.log(TAG, encryptedPunchline);

    Gdx.app.log(TAG, "How does GigaGal tie her shoelaces when her arms are cannons?");

    // TODO: Go find the text file in the android/assets directory
    // TODO: Get a FileHandle using Gdx.files.internal()
    FileHandle file = Gdx.files.internal("punchline");

    // TODO: Read the file using FileHandle.readString()
    String encrypted = file.readString();

    // TODO: Decrypt the punchline
    String punchline = decrypt(encrypted);

    // TODO: Log the rest of the joke
    Gdx.app.log(TAG, punchline);
}
 
Example 4
Source File: WorldIO.java    From TerraLegion with MIT License 6 votes vote down vote up
public static Player loadPlayer() {
	try {
		FileHandle handle = Gdx.files.external("player.save");
		if (!handle.exists()) {
			// not saved player yet
			return null;
		}

		String JSONString = handle.readString();

		JSONObject playerInfo = (JSONObject) new JSONParser().parse(JSONString);

		JSONObject playerPosition = (JSONObject) playerInfo.get("playerPosition");
		Player player = new Player(Float.parseFloat(playerPosition.get("x").toString()), Float.parseFloat(playerPosition.get("y").toString()));

		JSONObject jsonInventory = (JSONObject) playerInfo.get("playerInventory");

		Inventory inventory = JSONConverter.getInventoryFromJSON(jsonInventory);

		player.setInventory(inventory);
		return player;
	} catch(ParseException ex) {
		ex.printStackTrace();
	}
	return null;
}
 
Example 5
Source File: SimplifiedBeatmapLoader.java    From SIFTrain with MIT License 6 votes vote down vote up
private void loadAsyncStandard(AssetManager manager, String fileName, FileHandle file, BeatmapParameter parameter) {

        FileHandle handle = resolve(fileName);
        String jsonDefinition = handle.readString("UTF-8");
        SongFileInfo info = new SongFileInfo();
        try {
            info = new Gson().fromJson(jsonDefinition, SimpleSong.class);
        } catch (Exception e) {
            info = new SimpleSong();
            info.song_name = "Error: Invalid JSON format " + handle.file().getName();
            info.difficulty = 1;
        } finally {
            info.setFileName(fileName);
            // naming scheme for the resources is:
            // File Name[difficulty]
            // File Name [difficulty]
            // file_name_difficulty
            // this will allow the resource name to be parsed correctly and group the songs by resource
            info.setResourceName(handle.nameWithoutExtension().replaceAll("(_(easy|normal|hard|expert)|(\\s?\\[.+]))$", ""));
            beatmaps.add(info);
        }
    }
 
Example 6
Source File: SavedStuff.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
private void loadScore () {
	// Creates correct filename for scores file
	FileHandle handle;
	StringBuilder scoresFileBuilder = new StringBuilder();
	scoresFileBuilder.append(SCORES_STRING);
	scoresFileBuilder.append(String.valueOf(levelNumber));
	if (isFaster) {
		scoresFileBuilder.append(String.valueOf(fasterSpeed));
	} else {
		scoresFileBuilder.append(NO_FAST_STRING);
	}
	scoresFileBuilder.append(FILE_EXT);
	scoresFile = scoresFileBuilder.toString();

	// Checks if scores file exists, creates one if not
	if (Gdx.files.local(scoresFile).exists()) {
		handle = Gdx.files.local(scoresFile);
	} else {
		handle = Gdx.files.local(scoresFile);
		scoreString = Integer.toString(0);
		handle.writeString(scoreString, false);
	}

	scoreString = handle.readString();
	try {
		hiScore = Integer.parseInt(scoreString);
	} catch (NumberFormatException e) {
		hiScore = 0;
	}
}
 
Example 7
Source File: VfxGLUtils.java    From gdx-vfx with Apache License 2.0 5 votes vote down vote up
public static ShaderProgram compileShader(FileHandle vertexFile, FileHandle fragmentFile, String defines) {
    if (fragmentFile == null) {
        throw new IllegalArgumentException("Vertex shader file cannot be null.");
    }
    if (vertexFile == null) {
        throw new IllegalArgumentException("Fragment shader file cannot be null.");
    }
    if (defines == null) {
        throw new IllegalArgumentException("Defines cannot be null.");
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Compiling \"").append(vertexFile.name()).append('/').append(fragmentFile.name()).append('\"');
    if (defines.length() > 0) {
        sb.append(" w/ (").append(defines.replace("\n", ", ")).append(")");
    }
    sb.append("...");
    Gdx.app.log(TAG, sb.toString());

    String prependVert = prependVertexCode + defines;
    String prependFrag = prependFragmentCode + defines;
    String srcVert = vertexFile.readString();
    String srcFrag = fragmentFile.readString();

    ShaderProgram shader = new ShaderProgram(prependVert + "\n" + srcVert, prependFrag + "\n" + srcFrag);

    if (!shader.isCompiled()) {
        throw new GdxRuntimeException("Shader compile error: " + vertexFile.name() + "/" + fragmentFile.name() + "\n" + shader.getLog());
    }
    return shader;
}
 
Example 8
Source File: LogMenu.java    From Cubes with MIT License 5 votes vote down vote up
public void refresh() {
  FileHandle fileHandle = Gdx.files.absolute(FileLogWriter.file.getAbsolutePath());
  String string = "";
  try {
    string = fileHandle.readString();
  } catch (GdxRuntimeException e) {
    Log.error("Failed to refresh log menu", e);
  }
  label.setText(string);
  resize(Graphics.GUI_WIDTH, Graphics.GUI_HEIGHT);
}
 
Example 9
Source File: StateManager.java    From FruitCatcher with Apache License 2.0 5 votes vote down vote up
public StateBundle retrieveState() {
	FileHandle stateDataFile = Gdx.files.local(STATE_DATA_FILE);
	if( stateDataFile.exists() ) {
		Json json = new Json();
		try {
			String stateStr = stateDataFile.readString();
               return json.fromJson(StateBundle.class, stateStr );
           } catch( Exception e ) {
               Gdx.app.error( "StateManager", 
               		"Unable to parse existing game screen state data file", e );
           }
	}
	return null;
}
 
Example 10
Source File: SimpleSongLoader.java    From SIFTrain with MIT License 5 votes vote down vote up
public SimpleSong loadSong(SongFileInfo beatmap) {
    FileHandle handle = Gdx.files.absolute(Gdx.files.getExternalStoragePath() + "/" + beatmap.getFileName());
    SimpleSong song = null;
    String jsonDefinition = handle.readString("UTF-8");
    try {
        song = new Gson().fromJson(jsonDefinition, SimpleSong.class);
        validateSong(song);
        song.setValid(true);
        beatmap.song_name = song.song_name;
        if (errors.size() > 0) {
            beatmap.song_name = "Error: Beatmap format invalid. (" + handle.file().getName() + ")";
            song.setValid(false);
        }
    } catch (Exception e) {
        song = new SimpleSong();
        song.song_name = "Invalid JSON Format: " + handle.file().getName();
        song.difficulty = 1;
        beatmap.song_name = "Error: Invalid JSON Format. (" + handle.file().getName() + ")";
        errors.add("Invalid JSON Format");
        song.setValid(false);
    } finally {
        if (song != null) {
            song.setResourceName(handle.nameWithoutExtension().replaceAll("_(easy|normal|hard|expert)$", ""));
        }
    }
    return song;
}
 
Example 11
Source File: CocoStudioUIEditor.java    From cocos-ui-libgdx with Apache License 2.0 5 votes vote down vote up
public static List<String> getResources(FileHandle jsonFile) {
    dirName = jsonFile.parent().toString();

    if (!dirName.equals("")) {
        dirName += File.separator;
    }
    String json = jsonFile.readString("utf-8");
    Json jj = new Json();
    jj.setIgnoreUnknownFields(true);
    CCExport export = jj.fromJson(CCExport.class, json);
    return export.getContent().getContent().getUsedResources();
}
 
Example 12
Source File: TileMap.java    From Unlucky with MIT License 5 votes vote down vote up
public TileMap(int tileSize, String path, Vector2 origin, ResourceManager rm) {
    this.tileSize = tileSize;
    this.origin = origin;
    this.rm = rm;

    playerSpawn = new Vector2();

    // read file into a String
    FileHandle file = Gdx.files.internal(path);
    mapInfo = file.readString();
    // split string by newlines
    mapInfoLines = mapInfo.split("\\r?\\n");
    mapWidth = Integer.parseInt(mapInfoLines[0]);
    mapHeight = Integer.parseInt(mapInfoLines[1]);

    playerSpawn.set(Integer.parseInt(mapInfoLines[2]), Integer.parseInt(mapInfoLines[3]));

    dark = Integer.parseInt(mapInfoLines[4]) == 1;
    weather = Integer.parseInt(mapInfoLines[5]);

    bottomLayer = new TextureRegion[mapWidth * mapHeight];
    tileMap = new Tile[mapWidth * mapHeight];
    topLayer = new TextureRegion[mapWidth * mapHeight];

    createBottomLayer();
    createTileMap();
    createTopLayer();

    collisionMap = new boolean[mapWidth * mapHeight];
    for (int i = 0; i < collisionMap.length; i++) {
        collisionMap[i] = tileMap[i].isBlocked();
    }
}
 
Example 13
Source File: CocoStudioUIEditor.java    From cocos-ui-libgdx with Apache License 2.0 4 votes vote down vote up
/**
 * @param jsonFile     ui编辑成生成的json文件
 * @param textureAtlas 资源文件,传入 null表示使用小文件方式加载图片.
 * @param ttfs         字体文件集合
 * @param bitmapFonts  自定义字体文件集合
 * @param defaultFont  默认ttf字体文件
 */
public CocoStudioUIEditor(FileHandle jsonFile,
                          Map<String, FileHandle> ttfs, Map<String, BitmapFont> bitmapFonts,
                          FileHandle defaultFont, Collection<TextureAtlas> textureAtlas) {
    this.textureAtlas = textureAtlas;
    this.ttfs = ttfs;
    this.bitmapFonts = bitmapFonts;
    this.defaultFont = defaultFont;
    parsers = new HashMap<>();

    addParser(new CCButton());
    addParser(new CCCheckBox());
    addParser(new CCImageView());
    addParser(new CCLabel());
    addParser(new CCLabelBMFont());
    addParser(new CCPanel());
    addParser(new CCScrollView());
    addParser(new CCTextField());
    addParser(new CCLoadingBar());
    addParser(new CCTextAtlas());

    addParser(new CCLayer());

    addParser(new CCLabelAtlas());
    addParser(new CCSpriteView());
    addParser(new CCNode());

    addParser(new CCSlider());

    addParser(new CCParticle());
    addParser(new CCProjectNode());
    addParser(new CCPageView());

    addParser(new CCTImageView());

    actors = new HashMap<String, Array<Actor>>();
    actionActors = new HashMap<Integer, Actor>();

    //animations = new HashMap<String, Map<Actor, Action>>();

    actorActionMap = new HashMap<Actor, Action>();

    dirName = jsonFile.parent().toString();

    if (!dirName.equals("")) {
        dirName += File.separator;
    }
    String json = jsonFile.readString("utf-8");
    Json jj = new Json();
    jj.setIgnoreUnknownFields(true);
    export = jj.fromJson(CCExport.class, json);
}
 
Example 14
Source File: DemoMotionGdxAdapter.java    From thunderboard-android with Apache License 2.0 4 votes vote down vote up
public EmissiveShaderProvider(FileHandle vertexShader, FileHandle fragmentShader) {
    this(vertexShader.readString(), fragmentShader.readString());
}
 
Example 15
Source File: SavedStuff.java    From buffer_bci with GNU General Public License v3.0 4 votes vote down vote up
public void loadAllScoresIntoArray () {
	allScores = new int[NUMBER_OF_LEVELS][NUMBER_OF_SPEEDS];
	

	// Creates correct filename for scores file
	FileHandle handle;
	StringBuilder scoresFileBuilder = new StringBuilder();
	
	for(int x = 0; x < NUMBER_OF_LEVELS; x++) {
		for(int y = 0; y < NUMBER_OF_SPEEDS; y++) {
			levelNumber = x;
			fasterSpeed = y;
			if (fasterSpeed == NUMBER_OF_SPEEDS - 1) {
				isFaster = false;
			} else {
				isFaster = true;
			}
			
			scoresFileBuilder.setLength(0);
			scoresFileBuilder.append(SCORES_STRING);
			scoresFileBuilder.append(String.valueOf(levelNumber));
			if (isFaster) {
				scoresFileBuilder.append(String.valueOf(fasterSpeed));
			} else {
				scoresFileBuilder.append(NO_FAST_STRING);
			}
			scoresFileBuilder.append(FILE_EXT);
			scoresFile = scoresFileBuilder.toString();

			// Checks if scores file exists, creates one if not
			if (Gdx.files.local(scoresFile).exists()) {
				handle = Gdx.files.local(scoresFile);
			} else {
				handle = Gdx.files.local(scoresFile);
				scoreString = Integer.toString(0);
				handle.writeString(scoreString, false);
			}

			scoreString = handle.readString();
			try {
				hiScore = Integer.parseInt(scoreString);
			} catch (NumberFormatException e) {
				hiScore = 0;
			}
			allScores[levelNumber][fasterSpeed] = hiScore;
		}
	}	
	loadPreferencesAndScore();
}
 
Example 16
Source File: SavedStuff.java    From buffer_bci with GNU General Public License v3.0 4 votes vote down vote up
private void loadPreferences () {
	// Loads the preferences saved from the MainMenuScreen.
	String prefString;
	FileHandle prefHandle;
	if (Gdx.files.local(PREFERENCES_FILENAME).exists()) {
		prefHandle = Gdx.files.local(PREFERENCES_FILENAME);
	} else {
		prefHandle = Gdx.files.local(PREFERENCES_FILENAME);
		prefString = DEFAULT_PREF_STRING;
		prefHandle.writeString(prefString, false);
	}
	prefString = prefHandle.readString();

	char one = '1';
	// True if character at string index is '1', false if '0'
	isFaster = (one == prefString.charAt(0));
	isColor = (one == prefString.charAt(1));
	isAnimate = (one == prefString.charAt(2));
	isSound = (one == prefString.charAt(3));
	isOutline = (one == prefString.charAt(4));
	isPermOutline = (one == prefString.charAt(5));
	levelNumber = Character.getNumericValue(prefString.charAt(6));
	fasterSpeed = Character.getNumericValue(prefString.charAt(7));

	if (fasterSpeed == 0) {
		decreaseSpeed = UPDATE_SPEED_DECREASE_ZERO;
	} else if (fasterSpeed == 1) {
		decreaseSpeed = UPDATE_SPEED_DECREASE_ONE;
	} else if (fasterSpeed == 2) {
		decreaseSpeed = UPDATE_SPEED_DECREASE_TWO;
	} else if (fasterSpeed == 3) {
		decreaseSpeed = UPDATE_SPEED_DECREASE_THREE;
	} else if (fasterSpeed == 4) {
		decreaseSpeed = UPDATE_SPEED_DECREASE_FOUR;
	} else if (fasterSpeed == 5) {
		decreaseSpeed = UPDATE_SPEED_DECREASE_FIVE;
	}

	// Initital speed up
	timeToUpdate -= 5 * decreaseSpeed;
}
 
Example 17
Source File: ProjectController.java    From talos with Apache License 2.0 4 votes vote down vote up
public void loadProject (FileHandle projectFileHandle) {
    try {
        if (projectFileHandle.exists()) {
            FileTab prevTab = currentTab;
            boolean removingUnworthy = false;

            if (currentTab != null) {
                if (currentTab.getProjectType() == currentProject && currentTab.isUnworthy()) {
                    removingUnworthy = true;
                    clearCache(currentTab.getFileName());
                } else {
                    IProject tmp = currentProject;
                    currentProject = currentTab.getProjectType();
                    saveProjectToCache(projectFileName);
                    currentProject = tmp;
                }
            }
            currentProjectPath = projectFileHandle.path();
            projectFileName = projectFileHandle.name();
            loading = true;
            currentTab = new FileTab(projectFileName, currentProject); // trackers need to know what current tab is
            String string = projectFileHandle.readString();
            currentProject.loadProject(string);
            snapshotTracker.reset(string);
            reportProjectFileInterraction(projectFileHandle);
            loading = false;

            if (lastDirTracking) {
                TalosMain.Instance().Prefs().putString("lastOpen" + currentProject.getExtension(), projectFileHandle.parent().path());
                TalosMain.Instance().Prefs().flush();
            }

            TalosMain.Instance().UIStage().tabbedPane.add(currentTab);

            final Array<String> savedResourcePaths = currentProject.getSavedResourcePaths();
            TalosMain.Instance().FileTracker().addSavedResourcePathsFor(currentTab, savedResourcePaths);

            if (removingUnworthy) {
                safeRemoveTab(prevTab);
            }
        } else {
            //error handle
        }
    } catch (Exception e) {
        TalosMain.Instance().reportException(e);
    }
}