Save Array List to Text file - java

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);
}

Related

SceneBuilder JavaFX using a Textbox, create a new line as per comma, from data received

I am building a tradebot, and I created my own UI. I gather data about my account via the API, and setText into a text field (as image shows). What I want to do, is be able to create a new line using the commas as a break, or be able to make some sort of excel table to separate the data and make it easy to use.
When I call for the data, it just dumps everything into a long, line of text.
Any suggestions on how to achieve this?
thanks,
Arthur
#FXML
void onPositionClick(ActionEvent event)
{
Context ctx = new Context("https://api-fxpractice.oanda.com", "XXXXXXXXXXXXXXXXXXXXXX-YYYYYYYYYYYYYYYYYYYYYYYY");
try
{
AccountSummary summary = ctx.account.summary(
new AccountID("101-XXX-XXXXXX-XXX")).getAccount();
String summaryString = String.valueOf(summary);
displayResults.setText(summaryString);
} //end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
I would use System.lineSeparator() because its system-dependent:
String text = "abc,de,fghi,jklmn,o";
String newText = text.replaceAll(",", System.lineSeparator());
System.out.println(newText);
Output:
abc
de
fghi
jklmn
o

Saving files and preserving order during retrieve

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.

Java: Using File & Buffered Reader to fill an Array

So, I have my first Java project due in my new course this Sunday. One of the (most important) things we need to do is to fill 2 arrays with information read from a file. My professor said to use a file and buffered reader to do this.
Unfortunately, I've never used either.
For the first array I need to: Create a String array with 15 elements, then Read the state search data from the data file and store each item into the array.
The filename is 'states.search.txt' and contains the following.
California
Texas
AK
California
Indiana
Missippi
Jacksonville
Okalahooma
Florida
Maine
Hawaii
Puerto_Rico
FL
New_York
Auburn
The 2nd array is a lot more involved, so I'll ask separately for that one.
All help is appreciated!
You can read lines from file follow:
public static void main(String args[]) {
try {
List<String> states = new ArrayList(15)<>; // ArrayList is superstructure over array
FileInputStream fstream = new FileInputStream("C:\\states.search.txt");
String state;
while ((state = br.readLine()) != null) {
states.add(state);
}
in.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
But you have to turn on your brain to do your home work, it's better for you.

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