So I'm in the process of developing a Java IRC bot as a bit of a side project for a friend of mine, and while development is going well, I'm a little unsure as how to save the current state of certain variables in between sessions. It doesn't have a GUI, so I didn't think that it would be too complex, but my searching efforts have been futile thus far.
Thanks.
It will depend on the sort of variables you want to keep, but all methods will require you to write some sort data to a file.
If you only need to keep a handful of variables, you could consider implementing a .config file that could be a simple delimited text file.
If it's an entire object that you want to keep track of, say, a player in an irc game, one option you have is to parse the object into JSON, and save it to a textfile, for reading later. You can use Gson for this
example for a 'player' object:
public String savePlayer(String playerName){
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String playerFile = System.getProperty("user.dir")+"\\players\\"+playerName;
String jsonplayers = gsonPretty.toJson(players.get(playerName));
try{
FileWriter writer = new FileWriter(playerFile+".json");
writer.write(jsonplayers);
writer.close();
return "Player file saved successfully!";
}catch(Exception e){
e.printStackTrace();
}
return "Something went wrong";
}
you can then create a load method that either has the file name hard coded, or a string input to determine which file to load, and use something like:
playerFromJson = gson.fromJson(jsonString, Player.class);
to use that object in the code
Related
I'm passing an array of array to a java method and I need to add that data to a new file (which will be loaded into an s3 bucket)
How do I do this? I haven't been able to find an example of this
Also, I'm sure "object" is not the correct data type this attribute should be. Array doesn't seem to be the correct one.
Java method -
public void uploadStreamToS3Bucket(String[][] locations) {
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(String.valueOf(awsRegion))
.build();
String fileName = connectionRequestRepository.findStream() +".json";
String bucketName = "downloadable-cases";
File locationData = new File(?????) // Convert locations attribute to a file and load it to putObject
s3Client.putObject(new PutObjectRequest(bucketName, fileName, locationData));
} catch (AmazonServiceException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
You're trying to use PutObjectRequest(String,String,File)
but you don't have a file. So you can either:
Write your object to a file and then pass that file
or
Use the PutObjectRequest(String,String,InputStream,ObjectMetadata) version instead.
The later is better as you save the intermediate step.
As for how to write an object to a stream you may ask: Check this How can I convert an Object to Inputstream
Bear in mind to read it you have to use the same format.
It might be worth to think about what kind of format you want to save your information, because it might be needed to be read for another program, or maybe by another human directly from the bucket and there might be other formats / serializers that area easy to read (if you write JSON for instance) or more efficient (if you use another serializer that takes less space).
As for the type of array of array you can use the [][] syntax. For instance an array of array of Strings would be:
String [][] arrayOfStringArrays;
I hope this helps.
I've written my own 3D Game Engine and started writing a game. I am using OBJ-Models that use the TurboSquid Royalty Free License
Basically, it says that I can use their OBJ-Files but have to implement something that avoids the users to extract the OBJ-Files out of my program.
I've written a converter that extracts the information out of the OBJ-File and creates several float/integer arrays [vertices, vertexCoords, normals, tangents..., indices]
These arrays will be used later for creating the VAOs / VBOs. So my idea was to create a Java class called OBJModelData that contains these arrays. OBJModelDataimplements Serializable. My attempt was to save the class into a file and use them instead of the OBJ-File so that the user cannot see and use the content.
My attempt looks like this:
public void writeToFile(String file){
File f = new File(OBJLoader.RES_LOC+ file +".dat");
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(this);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This results in a file called modelName.dat and looks like this:
Obviously reverse engineering must be done the recreate my arrays. I just do not like the way its written. For example the class that has been serialized is written in the first line. If someone somehow manages the get the source files of my engine by doing some reverse engineering on that he could easily read the file.
Is my method save enough to avoid recreating the obj files and can I still use this method to fulfill the license conditions or is there any other way that is normally used (e.g. in other games/engines) ?
The end of your quote says: "without reverse engineering", so you do not need carry about reverse engineering. You need only "translate" from OBJ to another format of your creation, like you do.
I am trying to create a pet project for the summer, which requires a large amount of information. I think the best way to do this would be to store all the data in a text file, and proceed to pull the necessary information from that file when it's called upon. My question, though, is how to pull specific sets of information, and then proceed to store parts of that into an array perhaps or some other data structure which would allow for that to be more easily accessed during the execution of the program. The text file would have hundreds (if not thousands) of "sets" of data, and each "set" will have multiple parts. For example,
ID001 Name Data1 Data2 Data3 TypeData
Where ID001 would just be an index, the name would be a string, the three "Data" would be integers, and the TypeData would be a String (for example). What is the best way to go about taking all that information (there'll actually be more data per "set" but for simplicity's sake let's go with just this) and separating it so each part is usable by a different part of the program? Is this even the right way to go about doing something like this? I was originally imagining something along the lines of a spreadsheet but I don't know how to use something quite like that as I/O for a program.
Here's one possible way of reading a file and getting just the "chunks":
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
You can take a look at the Java Scanner Tutorial for other ideas.
I am new to Json and libGDX but I have created a simple game and I want to store player names and their scores in a Json file. Is there a way to do this? I want to create a Json file in Gdx.files.localStorage if it doesnt exist and if it does, append new data to it.
I have checked code given at :
1>Using Json.Serializable to parse Json files
2>Parsing Json in libGDX
But I failed to locate how to actually create a Json file and write multiple unique object values (name and score of each player) to it. Did I miss something from their codes?
This link mentions how to load an existing json but nothing else.
First of all i have to say that i never used the Libgdx Json API myself. But i try to help you out a bit.
I think this Tutorial on github should help you out a bit.
Basicly the Json API allows you to write a whole object to a Json object and then parse that to a String. To do that use:
PlayerScore score = new PlayerScore("Player1", 1537443); // The Highscore of the Player1
Json json = new Json();
String score = json.toJson(score);
This should then be something like:
{name: Player1, score: 1537443}
Instead of toJson() you can use prettyPrint(), which includes linebreaks and tabs.
To write this to a File use:
FileHandle file = Gdx.files.local("scores.json");
file.writeString(score, true); // True means append, false means overwrite.
You can also customize your Json by implementing Json.Serializable or by adding the values by hand, using writeValue.
Reading is similar:
FileHandle file = Gdx.files.local("scores.json");
String scores = file.readString();
Json json = new Json();
PlayerScore score = json.fromJson(PlayerScore.class, scores);
If you have been using a customized version by implementing Json.Serializable you have implemented the read (Json json, JsonValue jsonMap) method. If you implemented it correctly you the deserialization should work. If you have been adding the values by hand you need to create a JsonValuejsonFile = new JsonValue(scores). scores is the String of the File. Now you can cycle throught the childs of this JsonValue or get its childs by name.
One last thing: For highscores or things like that maybe the Libgdx Preferences are the better choice. Here you can read how to use them.
Hope i could help.
I am a newbie programmer, very newbie..
I am trying to write a program to test our website and am using Java and Selenium.
The issue is I want to create a "table" or a "reference" that will allow me to store variables that can easily be called back and used in different calls.
I tried to use a HashMap but found it was no good because when I rerun my testing code there is a new hashmap each time. I want something that can store the values and remember them the next time I run the code.
I looked at creating a mysql table but I can't figure out how to recall the variables out of the table once they have been created.
I hope this makes some sense. :0) Pls check out below if an example would be more useful
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Here is an example of the hashmap that I was using:
HashMap idTable = new HashMap();
idTable.put("GroupName", new String("Group " +
Long.toHexString(Double.doubleToLongBits(Math.random()))));
element = driver.findElement(By.id("name"));
element.sendKeys((String)idTable.get("GroupName"));
FYI: The reason this doesn't work for me is that I want to be able to wrap it in an "if" statement; to tell the computer that if the variable called "GroupName" already exists then don't do it again.. however every time I run the script I make a call to the function [HashMap idTable = new HashMap();] and I don't know how to NOT make that call because the HashMap isn't saved anywhere.. it is created new each time.
Thanks,
Orli
not sure where to add this: but following the first suggestion here is what I did.
HashMap idTable;
try{
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("C:\Documents and Settings\My Documents\Selenium local\hashmap.dat"));
idTable = (HashMap) is.readObject();
}
catch(Exception e){
idTable = new HashMap();
}
AND then:
try{
ObjectOutputStream os = new ObjectOutputStream (
new FileOutputStream("C:\Documents and Settings\My Documents\Selenium local\hashmap.dat"));
os.writeObject(idTable);
os.close();
}
catch (Exception e){
}
It works. :0) Thanks for the help!
Use an instance of Properties for simple string key/value pairs. It is a Map, like HashMap but has load and store methods for reading/writing its contents to a file. This should be more than adequate for simple testing usage.
It is commonly used for loading configuration files.
You must store them somewhere not in the code, as the code goes bye-bye whenever the JVM shuts down. Two good options to do this are
Using SQL database, research this more via google if you want
Via files, simply writing your HashMap database to a file at the end of your program (Do Runtime.addShutdownHook, and pass it a thread whcih stores your hashmap to the file), and have it read from the file at the begining of the code (if the file is nonexistant, make a new one, and store an empty hashmap to it)