Writing a HashMap to a text file Android studio - java

I have tried to use serialisation to write my HashMap into a text file but it just doesn't seem to work. I'm not sure if I'm using it wrong
my Hashmap :
HashMap lettersAvailable = new HashMap();
and my code I use for serialisation
public void onResume(){
super.onResume();
try
{
FileInputStream fileInputStream = new FileInputStream(getApplicationContext().getFilesDir()+"/FenceInformation.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map lettersAvailable = (Map)objectInputStream.readObject();
Toast.makeText(this,"Hashmap reloaded",Toast.LENGTH_SHORT);
}
catch(ClassNotFoundException | IOException | ClassCastException e) {
e.printStackTrace();
}
}
#Override
public void onPause(){
super.onPause();
try
{
FileOutputStream fos = getApplicationContext().openFileOutput("YourInfomration.ser", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(lettersAvailable);
oos.close();
Log.d(TAG, "onCreate() Restoring previous state");
} catch (IOException e) {
e.printStackTrace();
}
}
In the onResume method it says lettersAvailable variable is never used at Maps lettersAvailable
Is there not another way to do this?

Related

Appendable Binary File

I'm working on appending objects to a binary file. My file is:
File f=new File("person.dat");
I'm getting an error (java.io.StreamCorruptedException: invalid stream header: 79737200) when I attempt to open the binary file. As far as I can tell the program writes the data just fine, but as soon as I try reading from it, I get the above error. Any help is appreciated!
My Code to write:
AppendObjectOutputStream out = null;
try {
out = new AppendObjectOutputStream(new FileOutputStream(f, true));
out.writeObject(new Student(name, age));
out.flush();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
out.close();
}
My class for making appendable:
public class AppendObjectOutputStream extends ObjectOutputStream {
public AppendObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
#Override
protected void writeStreamHeader() throws IOException {
reset();
}
}
My partial code for reading and adding objects to an ArrayList:
Course course = new Course();
Student st = null;
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("person.dat"));
try
{
while (true)
{
st = (Student) in.readObject();
course.addAccount(st); //adds student object to an ArrayList in
//class Course
}
}
catch (EOFException ex) {
}
}
catch (Exception ex) {
ex.printStackTrace();
} finally {
in.close();
}
UPDATE:
Current code to read but its not printing anything to screen:
try(ObjectInputStream ois = new ObjectInputStream(
new BufferedInputStream(Files.newInputStream(f))))
{
while (ois.available() > 0)
{
st = (Student) ois.readObject();
studentlist.addAccount(st);
System.out.println(st.getStudentNumber());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
This is how I write to file:
Path f = Paths.get("person.dat");
try (ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(f, StandardOpenOption.APPEND))))
{
oos.writeObject(new Student(name,age));
}
catch(Exception ex)
{
ex.printStackTrace();
}
Rather than trying to fix your utility classes, I suggest to use the standard classes of the NIO.2 File API.
Try something like (untested):
Path personDataFilePath = Paths.get("person.dat");
// or Java 11:
// Path personDataFilePath = Path.of("person.dat");
try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(personDataFilePath, StandardOpenOption.APPEND)))){
oos.writeObject(new Student(name,age));
} catch (IOException ex) {
// do some error handling here
}
and to read the file, something like (untested):
List<Student> students = new ArrayList<>();
try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(personDataFilePath)))){
while (ois.available() > 0){
students.add((Student) ois.readObject());
}
} catch (IOException ex) {
// do some error handling here
}
I have modified the code to work around making a file "appendable". I write a single arraylist object to the file (the arraylist holds a list of student objects). When I want to add a student, I read the object (arraylist) from the file, add my new student to the arraylist and write the arraylist back to the file. It is now working and my file does not have an append format.

updating ini file in java using rest webservice

I need to update ini file in java using rest service.I could read file in browser but have no idea how to update it.Can anybody please help for the required method that would update my ini file.
dbform.java
public class dbform {
public List<db> getAlldb(){
List<db> dbList = null;
try {
File file = new File("test.ini"); // read ini file
if (!file.exists()) {
db DB = new db("dbname: test","password: test");
dbList = new ArrayList<db>();
dbList.add(DB);
savedbList(dbList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
dbList = (List<db>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return dbList;
}
private void savedbList(List<db> dbList){
try {
File file = new File("test.ini");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dbList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try to use ini4j.
The [ini4j] is a simple Java API for handling configuration files in Windows .ini format. Additionally, the library includes Java Preferences API implementation based on the .ini file.
http://ini4j.sourceforge.net/
Check your code there seems to be some issue in the way you have called the function. You don't seem to be passing the dbList into the replaceData() function. Probably it will be something like this
public void replaceData(List<db> dbList){ return DBform.savedbList(dbList); }

Saving Class Type info to file for later use

As you know, passing class types is important when programming Android applications.
One simple example is using an Intent.
Intent i = new Intent(this, MyActivity.class);
So it'll be kind of useful in some situations if I can save the class type info to a file for later use, for instance, after reboot.
void saveClassTypeInfo(Class<?> classType, String filename) {
String str = null;
// Some job with classType
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
fos.write(str.getBytes());
fos.close();
} catch (Exception e) {
}
}
If I could save in a certain way like above, then I would be able to put it back to an Intent like this in the future.
Intent i = new Intent(this, restoredClassInfoFromFile);
How I can achieve this kind of job? Because Class<?> is not an object, I don't know where to start at all.
[EDIT]
.class is an object too, so we can save it just like saving an object.
This is possible using ObjectOutputStream here SaveState is your Custom class
public static void saveData(SaveState instance){
ObjectOutput out;
try {
File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.ser");
out = new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(instance);
out.close();
} catch (Exception e) {e.printStackTrace();}
}
public static SaveState loadData(){
ObjectInput in;
SaveState ss=null;
try {
in = new ObjectInputStream(new FileInputStream("appSaveState.ser"));
ss=(SaveState) in.readObject();
in.close();
} catch (Exception e) {e.printStackTrace();}
return ss;
}
Full Tutorial write to File available here
And Read Object from File here

Serializing ArrayList android not working

UPDATE: After a bit of testing I've determined the file itself isnt being created, at least according to the file.exists check anyway. Any ideas?
Hi I'm trying to serialize an arraylist when my app is exited and read it back when its resumed. It doesnt seem to be creating the file.
Here is my code.
protected void onPause() {
super.onPause();
if(!myArrayList.isEmpty())
{
final String FILENAME = "myfile.bin";
try{
FileOutputStream fos;
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
//FileOutputStream fileStream = new FileOutputStream(FILENAME);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(myArrayList);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
#SuppressWarnings("unchecked")
#Override
protected void onResume() {
super.onResume();
File file = new File("myfile.bin");
if(file.exists()){
final String FILENAME="myfile.bin";
try{
FileInputStream fileStream = new FileInputStream(FILENAME);
ObjectInputStream os = new ObjectInputStream(fileStream);
myArrayList = (ArrayList<MyObject>)os.readObject();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
Any ideas? My MyObject class implements serializable.
Got it to work by changing FileInputStream fileStream = new FileInputStream(FILENAME) to FileInputStream fileStream= openFileInput(FILENAME).
os.writeObject(myArrayList);
os.flush();
os.close();
Try os.close() immediately after writeObject, it should call flush() anyways.

android what is wrong with openFileOutput?

I'm trying to use openFileOutput function but it doesn't compile and doesn't recognize the function. I'm using android sdk 1.6. Is this a sdk problem ? Is this a parameter problem ?
import java.io.FileOutputStream;
public static void save(String filename, MyObjectClassArray[] theObjectAr) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObjectAr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
Your method should be as follows. Takes in an extra Context as a parameter. To this method you can pass your Service or Activity
public static void save(String filename, MyObjectClassArray[] theObjectAr,
Context ctx) {
FileOutputStream fos;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObjectAr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
You're trying invoke non-static method from static context (your method has static modifier). You either have to make your method to be non-static or to pass in an instance of Context (activity instance in most cases) and invoke the method on the object.
Also you can't openOutputStream on a path. It causes this exception:
java.lang.IllegalArgumentException: File /storage/sdcard0/path/to/file.txt contains a path separator
To fix this you need to create a file object and just create it like this:
String filename = "/sdcard/path/to/file.txt";
File sdCard = Environment.getExternalStorageDirectory();
filename = filename.replace("/sdcard", sdCard.getAbsolutePath());
File tempFile = new File(filename);
try
{
FileOutputStream fOut = new FileOutputStream(tempFile);
// fOut.write();
// fOut.getChannel();
// etc...
fOut.close();
}catch (Exception e)
{
Log.w(TAG, "FileOutputStream exception: - " + e.toString());
}
You can use openFileOutput in static Class if you pass View as below:
public static void save(View v, String fileName , String message){
FileOutputStream fos = null;
try {
fos = v.getContext().openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(message.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources