Write and read binaries in Android

I created a custom type object Taskand want to save it in a binary file in internal memory. Here is the class I created:

public class Task {

    private String title;
    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;

    public Task(String inputTitle, int inputYear, int inputMonth, int inputDay, int inputHour, int inputMinute) {

        this.title = inputTitle;
        this.year = inputYear;
        this.month = inputMonth;
        this.day = inputDay;
        this.hour = inputHour;
        this.minute = inputMinute;

    }

    public String getTitle() {

        return this.title;

    }

    public int getYear() {

        return this.year;

    }

    public int getMonth() {

        return this.month;

    }

    public int getDay() {

        return this.day;

    }

    public int getHour() {

        return this.hour;

    }

    public int getMinute() {

        return this.minute;

    }
}

In the exercise, I created a method that will save my object to a file. This is the code I used:

public void writeData(Task newTask) {
    try {
        FileOutputStream fOut = openFileOutput("data", MODE_WORLD_READABLE);
        fOut.write(newTask.getTitle().getBytes());
        fOut.write(newTask.getYear());
        fOut.write(newTask.getMonth());
        fOut.write(newTask.getDay());
        fOut.write(newTask.getHour());
        fOut.write(newTask.getMinute());
        fOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Now I would like to create a method that will extract data from a file. While reading on the Internet, many people use it FileInputStream, but I am having problems extracting bytes from it and knowing how long a string can be. In addition, I used a simple method found on the Internet, but I was denied permission. As I said, I am very new to Android development.

public void readData(){
    FileInputStream fis = null;
    try {
        fis = new FileInputStream("data");
        System.out.println("Total file size to read (in bytes) : "
                + fis.available());
        int content;
        while ((content = fis.read()) != -1) {
            // convert to char and display it
            System.out.print((char) content);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Any help would be appreciated.

+4
source share
3

, SD-.

Environment.getExternalStorageDirectory()

. "/data/local/", . ,

DataInputStream,

File file = new File("myFile");
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();

- ,

import java.io.*;
public class Sequence {
    public static void main(String[] args) throws IOException {
    DataInputStream dis = new DataInputStream(System.in);
    String str="Enter your Age :";
    System.out.print(str);
    int i=dis.readInt();
    System.out.println((int)i);
    }
}

Serializable . , , , ( ). ,

import java.io.*;
import java.util.*;
import java.util.logging.*;

/** JDK before version 7. */
public class ExerciseSerializable {

  public static void main(String... aArguments) {
    //create a Serializable List
    List<String> quarks = Arrays.asList(
      "up", "down", "strange", "charm", "top", "bottom"
    );

    //serialize the List
    //note the use of abstract base class references

    try{
      //use buffering
      OutputStream file = new FileOutputStream("quarks.ser");
      OutputStream buffer = new BufferedOutputStream(file);
      ObjectOutput output = new ObjectOutputStream(buffer);
      try{
        output.writeObject(quarks);
      }
      finally{
        output.close();
      }
    }  
    catch(IOException ex){
      fLogger.log(Level.SEVERE, "Cannot perform output.", ex);
    }

    //deserialize the quarks.ser file
    //note the use of abstract base class references

    try{
      //use buffering
      InputStream file = new FileInputStream("quarks.ser");
      InputStream buffer = new BufferedInputStream(file);
      ObjectInput input = new ObjectInputStream (buffer);
      try{
        //deserialize the List
        List<String> recoveredQuarks = (List<String>)input.readObject();
        //display its data
        for(String quark: recoveredQuarks){
          System.out.println("Recovered Quark: " + quark);
        }
      }
      finally{
        input.close();
      }
    }
    catch(ClassNotFoundException ex){
      fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
    }
    catch(IOException ex){
      fLogger.log(Level.SEVERE, "Cannot perform input.", ex);
    }
  }

  // PRIVATE 

  //Use Java logging facilities to record exceptions.
  //The behavior of the logger can be configured through a
  //text file, or programmatically through the logging API.
  private static final Logger fLogger =
    Logger.getLogger(ExerciseSerializable.class.getPackage().getName())
  ;
} 
+9

, , . , , - - , .

Serializable interface, writeObject() readObject().

XML -, .

0

Android . . ( ) , . ( , .)

, getFilesDir() , ( ). , readData() writeData(). getFilesDir(), , readData() writeData().

( ). , , Android . , getFilesDir(), . , , , , .

File myStorageFolder = new File(context.getFilesDir(), "myStorageFolder");

(I agree with P basak that DataInputStreamboth DataOutputStreamis your best option for reading and writing data. I do not recommend serialization, except for a very narrow set of applications where portability is a factor because it is very inefficient. In my case, the objects that occupied 15 seconds to download via Serialization, downloaded in less than 2 seconds using DataInputStream.)

0
source

All Articles