Saving files and preserving order during retrieve - java

In my note taking app, as soon as user adds a note, I save it using using the following code :
public void saveNote(String note, String noteCreationDate) {
// Name file with current date
FileOutputStream outputStream;
try {
outputStream = openFileOutput(noteCreationDate, Context.MODE_PRIVATE);
outputStream.write(note.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
However when I load the notes using
String[] allNotes = fileList();
then iterate one by one and add it to List and attach it to adapter, the order of the items in the RecyclerView is changed.
How do I preserve the order.
thanks

The better solution is to store the notes in a more appropriate way, like SharedPreferences or a database.
As a workaround, you can sort the file names obtained from fileList() method.
String[] allNotes = fileList();
Arrays.sort(allNotes);
// Iterate over the files
You also should use the file names with a proper date format, like ISO 8601: yyyy-MM-dd'T'HH:mm'Z' to guarantee the alphabetical order.

Related

Writing Strings to a binary file java

I have a list of objects that has some simple String properties. I want to be able to save those strings to binary so that when you open the file outside the program, you only see 1's and 0's.
I have managed to use FileOutputStreamand saved the strings, however, I can't manage to get it to write to binary. The file reads as clean readable text. I have tried getBytes().
What would be the best approach for this? Keep in mind that I want to be able to read the file later and construct back the objects. Would it be better to use Serializable and save a list of objects?
Here is my FileWriter:
NB: The toString() is custom and returns a String with linebreaks for every property.
public class FileWriter {
public void write(String fileName, Savable objectToSave ) throws IOException {
File fileToSave = new File(fileName);
String stringToSave = objectToSave.toString();
byte[] bytesToSave = stringToSave.getBytes(StandardCharsets.UTF_8) ;
try (
OutputStream outputStream = new FileOutputStream(fileToSave);
) {
outputStream.write(bytesToSave);
} catch (IOException e) {
throw new IOException("error");
}
}
}
If your goal is simply serializing, implementing Serializable and writing them would work, but your string is still going to be readable. You can encrypt the stream, but anyone decompiling your code can still devise a way to read the values.

Save Array List to Text file

I've spent all day on this and need some advice!
I'm trying to save the contents of a Array List into a text file.
I have got android to save the array list contents to an internal *.txt however after entering "Test one" and "Test Two" into the array list, and a button is clicked to save the current contents into the text file. I get the following:
�� sr java.util.ArrayListx����a� I sizexp w t Test Onet Test Twox
An Error is also given which is:
"File was loaded in the wrong encoding:'UTF-8'
The System.out.print gives the results:
"I/System.out: [Test One, Test Two]"
which is accurate to show the contents of the array list.
Code used:
public void savingfile() {
read = (Button)findViewById(R.id.read);
read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
outputStream = openFileOutput(anxfile, Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(outputStream);
out.writeObject(arrayList);
System.out.println(arrayList);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Many thanks, Leon
P.S. I have tried many youtube tutorials/Stackoverflow answers to fix the problem but still having the same issue
The list contains Strings, right?
If so, then instead of writing the object into your stream:
out.writeObject(arrayList);
You may want to dig out the Strings from the List first and write them:
for (String text : arrayList) {
out.writeObject(text);
}

How to append data to File using SuperCSV using CsvListWriter

I have a method to write data to a file.
public void writeCSFFileData(List<String> fileData){
try {
CsvListWriter csvWriter = new CsvListWriter(new FileWriter("/path/file.csv"), CsvPreference.STANDARD_PREFERENCE);
csvWriter.write(fileData);
csvWriter.close();
} catch (Exception e) {
SimpleLogger.getInstance().writeError(e);
}
The above method is called several times to write to a file.
But, each time the file is not appended instead it is overwritten.
Thanks in advance.
I found the solution myself, I just need to add true in FileWriter to append the data.
Ex: new FileWriter("/path/file.csv",true)

How to load content of a text file and display it using ListView?

[I'm quite new with Android programming so please excuse me for my nooby questions]
I'm developing a dictionary app. One of this app's feature is the Favourite button which allows user to save favourite words (short-click) and view the list of favourite words (long-click).
So far, I have succeeded in saving words into a text file (myfav.txt). The format of the content of the text file is as below (each item on a line):
A
B
C
...
Z
However, I have problem in loading and viewing this file inside my app. I'm thinking of using ListView to display the content of "myfav.txt" but I don't really know what to do. I have consulted the Qs & As from other similar posts here but found myself more confused as a result.
Therefore, my questions are:
How can I load content of "myfav.txt" and display it using ListView? Could you please give detailed instructions as for beginners?
Are there any better ways to do view the content of "myfav.txt" other than ListView?
Here is my code:
//Reading lines from myfav.txt
btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
File sdcard = Environment.getExternalStorageDirectory();
setContentView(R.layout.text_view);
//trying opening the myfav.txt
try{
File f = new File(sdcard,"myfolder/myfav.txt");
InputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
while((readString = buf.readLine())!= null){
Log.d("Content: ", readString);
//How to code to load/view the content of "myfav.txt"
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return false;
}
});
Thank you very much indeed.
Hi you can find useful example here.
I do not think it's a good idea to use ListView for it. You'll need to provide ListAdapter if you choose this way.
I'd recommend using TextView (if you don't need to edit your text) or EdiText (if you do)
Using a file to save such information is not too sophisticated. I think you should look into tutorials about using SQLite, so you can store the words in a databse, and use cursors to view them in ListViews. You could use a separate boolean coloumn in you schema to mark favourited words that way for example.
Anyways, if you want to stick with files, one solution would be:
Read the contents of the file into a String array. You can use e.g. the Scanner class to easily read in lines from the file, and store them as separate strings in this array.
Construct a simple ArrayAdapter adapter class using this array.
Assign this adapter to a ListView.
Profit.
I am using following for writing to file -
FileOutputStream fout = null;
try {
fout = openFileOutput(fileName, MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(wordList); //writing arraylist<T>
oos.flush();
} catch(IOException e)
{
e.printStackTrace();
}
For reading -
fin = openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
list =(ArrayList<T>)ois.readObject(); //reading in arraylist directly

Serialization and Data Structures

Hi all I need an advice.
I'll explain my problem. I want take data from web , elaborate the result, keep it and serialize on file.
I need to restore and use data from file , somehow. I dont want that file is been overwritten and lose old data.I need have a sort of list of Object in the File where i can search the last , use Method of another class to find some values etc , insert or similar, etc.....
In this case i used ArrayList but i dont know if it was the best choise.
I tried to do this but i have a problem know. In the specific if use a Class called Data and i want a serilizate file that keep ArrayList. So when i call method save(Object obj) of FileStructureClass(a class that i made to save, load file ) in this method i need to check if file already has an ArrayList so if it's true i can add in that Arraylist the Object , passed as parameter , else i return a new ArrayList. Of course i do a cast from Object to Data Class when i add in ArrayList.
I would fix this problem and then after find a better solution (if there is) to my problem.
The Data Class contains only 3 String and 1 GregoriusCalendar. Keep in mind(for the choise as ArrayList as Solution) that i need save file 1 time at day(i do a check with last element of the arraylist and do check with actual GregoriusCalendar..if past 1 day i can insert the element in arraylist).
After Explain the situation i list my problems
When i try to save for the FIRST time a Data Object in the Arraylist i have an error java.io.EOFException , i think that the problem is in tmp= ArrayList)ois.readObject(); but i cant find a solution. Dont happen when i insert manually a DataObject in the ArrayList and i use a method to insert a second one
According to you , ArrayList is a valid solution for my situation?
This method check if the file has data or not.
If it's empty i create a new one ArrayList and return it
otherwise i read the ArrayList already store in the file , and i return it
public ArrayList<Dati> check() {
ArrayList<Dati> tmp = new ArrayList<Dati>();
ObjectInputStream ois;
try{
fileInput = new FileInputStream("prova.dat");
ois = new ObjectInputStream(fileInput);
if (ois.readObject() == null) {
Logger.getLogger("file is empty");
ois.close();
return tmp;
}
//The error that i recive arrives from the under line
// (Impossible load file check method: java.io.EOFException
tmp = (ArrayList<Dati>) ois.readObject();
ois.close();
} catch (IOException e) {
System.out.println("Impossibile caricare i dati metodo check: "+e);
}
catch (ClassNotFoundException e) {
System.err.println("error");
}
return tmp;
}
//This method recive data of file that contains ArrayList<Data>
// and add to this a Data Object gave as Parameter
public void save(Object obj){
try{
ArrayList<Data> temp = check();
temp.add((Data) obj);
ObjectOutputStream os =
new ObjectOutputStream(new FileOutputStream("prova.dat"));
os.writeObject(temp);
os.flush();
os.close();
}
catch(IOException e){
System.out.println("Impossible save datas: "+e);
}
}
public Object load(String path){
Object obj=null;
try{
fileInput=new FileInputStream(path);
ois=new ObjectInputStream(fileInput);
obj=ois.readObject();
ois.close();
}
catch(IOException e){
System.out.println("Impossible load file: "+e);
}
catch(ClassNotFoundException e){
System.err.println();
}
return obj;
}
When i try to save for the FIRST time a Data Object in the Arraylist
i have an error java.io.EOFException , i think that the problem is
in tmp= (ArrayList)ois.readObject(); but i cant find a solution. Dont
happen when i insert manually a DataObject in the ArrayList and i
use a method to insert a second one
This seems to be correct. Looking at javadoc, it does seem like ois.readObject() returns null when there is nothing in the file. One approach I can think of is to initialize the file with an empty ArrayList in setup phase.
According to you , ArrayList is a valid solution for my situation?
I don't see why not. But it depends on what you will do with the list after reading it. If you have to search it often and it is large then you may consider a different data structure.

Categories