How do I save a float to a file using android java? - java

I have a simple game in which I would need to store a highscore (float) to a file and then read it next time the user goes on the app. I want it to be saved on the device, however, I have found no way to do that. How can I persist data on the device to a chosen location ?

You can use internal storage. This will create files that can be written to and read from. The best way to do this is to create a separate class that handles files. Here are two methods that will read and write the highscore.
To set the highscore, use setHighScore(float f).
public void setHighScore(float highscore){
FileOutputStream outputStream = null;
try {
outputStream = (this).openFileOutput("highscore", Context.MODE_PRIVATE);
outputStream.write(Float.toString(f)).getBytes());
outputStream.close();
} catch (Exception e) {e.printStackTrace();}
}
To get the highscore, use getHighScore().
public float getHighScore(){
ArrayList<String> text = new ArrayList<String>();
FileInputStream inputStream;
try {
inputStream = (this).openFileInput("highscore");
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr);
String line;
while ((line = bufferedReader.readLine()) != null) {
text.add(line);
}
bufferedReader.close();
} catch (Exception e) { e.printStackTrace();}
return Float.parseFloat(text.get(1));
}

Using File Handling -
I would suggest going basic by using a file handling technique. Auto create a text file using the java's InputStream and OutputStream classes. Then add the float inside it. As suggested in the comments above too.
Using properties files -
Refer this code - http://www.mkyong.com/java/java-properties-file-examples/
Using a database -
You can go ahead and use a database which will safely store the score and make sure no one tampers with it easily. Tutorial for this - http://www.tutorialspoint.com/jdbc/

Try simple with very few lines.
public void saveHighScore(File file, float highScore){
try{
Formatter out = new Formatter(file);
out.format("%f", highScore);
out.close();
}catch(IOException ioe){}
}

Related

remove black diamond with a question mark text from android sdcard file

I am creating a listview with json data.When user is offline I want to show the data in listview. I have stored the json data in android sdcard. And I retrive the data when user is offline and showed it in listview. The problem is, when I read the file from directory it's show's me black diamond with a question mark and stores it in array list. this type of "����t��*" my question is how to remove this type of string from Arraylist. Someone please help
Save the Data:
public void saveMyData()
{
try {
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+"cachefile.txt"));
out.writeObject(al.toString());
Toast.makeText(getApplicationContext(), "Data Saved..",Toast.LENGTH_LONG).show();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my retrieving code.
String fileContent = "";
try {
String currentLine;
BufferedReader bufferedReader;
FileInputStream fileInputStream = new FileInputStream(getFilesDir()+"cachefile.txt");
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream,"UTF-8"));
while ((currentLine = bufferedReader.readLine()) != null) {
fileContent += currentLine + '\n';
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
Log.d("FAILED","THOS IS NULL");
fileContent = null;
}
Log.d("SUCESS","SUCESS BUDDYY"+fileContent);
Broadly speaking, the issue is that you're using an ObjectOutputStream to write your data to the file, but a BufferedReader to read it back in. The ObjectOutputStream is specifically designed to allow objects and native data types to be written to a stream in a way they can be read back in via an ObjectInputStream to reconstitute the objects in the same way. This encoding is not meant to be human readable and usually contains extra characters as field separators.
I don't know what al is, but since you're calling toString() before you write it, I can assume that you want actual strings in a file you can read. To do this, you probably want to use a PrintStream and the PrintStream.println() method instead of the ObjectOutputStream.

Location of text files in android project

I want to read and write some data from text ( .txt ) files in my android project. ( The files are going to be included in the project itself for storing some user preference data )
I want to use only PURE JAVA PROVIDED METHODS to do that, like -
Scanner myScanner = new Scanner( new File( "file_name.txt" ) );.
These are a few static data in a non-activity class. So i don't have any Context to use for calling getResources() or using SharedPreferences. And there is no way i can pass a context from elsewhere to the class. I'm not going to explain why cause it's going to be a long story. Please don't give any suggestions regarding these ways.
My question is simple - if I want to read/write files with java methods, exactly where do i need to put them in my project?
I AM USING ANDROID STUDIO.
I start with reading a simple text.txt, you first have to upload a file in an asset folder after that you create a Private String method
private String readFileFromAssets(String filename) {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(
getAssets().open(filename)));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
return builder.toString();
} catch (FileNotFoundException e) {
displayMessage("File not found: " + e.getMessage());
} catch (Exception e) {
displayMessage(e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
displayMessage(e.getMessage());
}
}
}
return null;
}
give me a feedback about it.

Java -- Need help to enhance the code

I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.

How to add a line in a text file without overwriting it (JAVA)?

My data is stored in an ArrayList whose size increases during program execution.
I managed to save all the data whenever the size increases, but this brings me to overwrite the data already stored.
The solution is to go directly to the bottom line and insert the contents of the last cell of ArrayList. Unfortunately I do not know how to implement it.
Thank you for helping me to do this.
Below is the method I used.
private void SaveLocationData(){
try {
FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(LocationList.size());
for (Location location : LocationList) {
dout.writeUTF(location.getLatitude() + "," + location.getLongitude());
}
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
} catch (IOException exc) {
exc.printStackTrace();
}
}
Use MODE_APPEND:
FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_APPEND);
From the doc:
File creation mode: for use with openFileOutput(String, int), if the
file already exists then write data to the end of the existing file
instead of erasing it.
You can try this too
FileWriter fstream = new FileWriter("x.txt",true); //this will allow to append
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write("append txt...");
fbw.newLine();
fbw.close();

Reading a line of a txt file in assets

I have a text file placed in assets and I want to read one line of it at a time. My problem is that I do not know how to access the file in Activity, and then once I access it, how would I go about only selecting one line?
If keeping the txt file in assets is a bad idea, where should I put it for easier access?
I really appreciate any help!
This is a snippet I use to prepopulate tables in my RSS feed reader. You can use it as a track for your needs.
In res/raw/ I have file feeds.txt. The file is referenced is code like R.raw.feeds.
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.feeds);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 8192);
try {
String line;
while ((line = reader.readLine()) != null) {
//make the use you want with "line"
}
} catch (IOException e) {
Log.e(TAG, "Error loading sample feeds.");
throw new RuntimeException(e);
}
To open assests, you'll need to call
<context>.getAssets().open(<your file>);
<context> is your activity, so if this is in your onCreate, then it would be this. That call returns an inputstream, which you can then handle however you please.
I don't see how it would be a particularly bad idea to keep your text file there, depends on what you're using that text file for.
Try this:
Make a new method for example readMyFile().
It must looks like this:
private String readMyFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder txt = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
txt.append(line);
txt.append("\n");
}
reader.close();
return txt.toString();
Paste it to your code, and use the method (readMyFile([the file what you want to read in assets]).
Hope it helps.

Categories

Resources