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

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.

Related

How do I save a float to a file using android 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){}
}

Writing Into a file using Java

public static void writeIntoFile() {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
fileOutputStream = new FileOutputStream("Employee.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(list1);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream == null) {
System.out.println("file is not created");
}
if (objectOutputStream == null) {
System.out.println("cant able to write");
}
}
}
I want to using this function to writing in a file. it writes successfully but it display data in bytecode. how can I save it into string format?
Use a FileWriter wrapped inside a BufferedWriter to write character data to a File.
ObjectOutputStream is used for serialization and results in a binary encoded file. Its only useful if you only want to load the file through your program and do not wish to read its contents elsewhere like in an external editor.
You also need to iterate through your List and save the requisite properties of your underlying Object in a format you wish to parse your File later on in. For example, as CSV (comma separated values) every Employee object and its properties would be persisted as one single line in the output file.
BufferedWriter br = new BufferedWriter(new FileWriter("Employee.csv"));
for (Employee employee : list) {
br.write(employee.getFName() + ", " + employee.getLName());
br.newLine();
}
br.close();
in the function writeIntoFile is write a Serialization Object into file
you should use the object's toString() to write a String into file
you can change bytecode into string using one simple way.
pass the bytecode into string constructor
like this:
new String(bytecode object);
and then write string object into file.

How to write or append string in loop in a file in java?

I'm having memory problem as working with very large dataset and getting memory leaks with char[] and Strings, don't know why! So I am thinking of writing some processed data in a file and not store in memory. So, I want to write texts from an arrayList in a file using a loop. First the program will check if the specific file already exist in the current working directory and if not then create a file with the specific name and start writing texts from the arrayList line by line using a loop; and if the file is already exist then open the file and append the 1st array value after the last line(in a new line) of the file and start writing other array values in a loop line by line.
Can any body suggest me how can I do this in Java? I'm not that good in Java so please provide some sample code if possible.
Thanks!
I'm not sure what parts of the process you are unsure of, so I'll start at the beginning.
The Serializable interface lets you write an object to a file. Any object that implemsents Serializable can be passed to an ObjectOutputStream and written to a file.
ObjectOutputStream accepts a FileOutputStream as argument, which can append to a file.
ObjectOutputstream outputStream = new ObjectOutputStream(new FileOutputStream("filename", true));
outputStream.writeObject(anObject);
There is some exception handling to take care of, but these are the basics. Note that anObject should implement Serializable.
Reading the file is very similar, except it uses the Input version of the classes I mentioned.
Try this
ArrayList<String> StringarrayList = new ArrayList<String>();
FileWriter writer = new FileWriter("output.txt", true);
for(String str: StringarrayList ) {
writer.write(str + "\n");
}
writer.close();
// in main
List<String> SarrayList = new ArrayList<String>();
.....
fill it with content
enter content to SarrayList here.....
write to file
appendToFile (SarrayList);
.....
public void appendToFile (List<String> SarrayList) {
BufferedWriter bw = null;
boolean myappend = true;
try {
bw = new BufferedWriter(new FileWriter("myContent.txt", myappend));
for(String line: SarrayList ) {
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (bw != null) try {
bw.close();
} catch (IOException ioe2) {
// ignore it or write notice
}
}
}

Reading in text file in Java

I wrote some code to read in a text file and to return an array with each line stored in an element. I can't for the life of me work out why this isn't working...can anyone have a quick look? The output from the System.out.println(line); is null so I'm guessing there's a problem reading the line in, but I can't see why. Btw, the file i'm passing to it definitely has something in it!
public InOutSys(String filename) {
try {
file = new File(filename);
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public String[] readFile() {
ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically
try {
String line;
// Read in lines of the document until you read a null line
do {
line = br.readLine();
System.out.println(line);
dataList.add(line);
} while (line != null && !line.isEmpty());
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Convert the ArrayList into an Array
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
// Test
for (String s : dataArr)
System.out.println(s);
return dataArr; // Returns an array containing the separate lines of the
// file
}
First, you open a FileWriter once after opening a FileReader using new FileWriter(file), which open a file in create mode. So it will be an empty file after you run your program.
Second, is there an empty line in your file? if so, !line.isEmpty() will terminate your do-while-loop.
You're using a FileWriter to the file you're reading, so the FileWriter clears the content of the file. Don't read and write to the same file concurrently.
Also:
don't assume a file contains a line. You shouldn't use a do/while loop, but rather a while loop;
always close steams, readers and writers in a finally block;
catch(Exception) is a bad practice. Only catch the exceptions you want, and can handle. Else, let them go up the stack.
I'm not sure if you're looking for a way to improve your provided code or just for a solution for "Reading in text file in Java" as the title said, but if you're looking for a solution I'd recommend using apache commons io to do it for you. The readLines method from FileUtils will do exactly what you want.
If you're looking to learn from a good example, FileUtils is open source, so you can take a look at how they chose to implement it by looking at the source.
There are several possible causes for your problem:
The file path is incorrect
You shouldn't try to read/write the same file at the same time
It's not such a good idea to initialize the buffers in the constructor, think of it - some method might close the buffer making it invalid for subsequent calls of that or other methods
The loop condition is incorrect
Better try this approach for reading:
try {
String line = null;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
System.out.println(line);
dataList.add(line);
}
} finally {
if (br != null)
br.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