Write and read binary files in Android

前端 未结 3 510
执念已碎
执念已碎 2021-01-13 17:25

I created a custom object of type Task and I want to save it in a binary file in internal storage. Here is the class I created:



        
相关标签:
3条回答
  • 2021-01-13 18:01

    Android provides a private directory structure to each application for exactly this kind of data. You don't need special permissions to access it. The only caveat (which is generally a good caveat) is that only your app can access it. (This principle is part of the security that prevents other apps from doing bad things to you.)

    If this meets you need for storage, just call getFilesDir() from whatever context is readily available (usually your activity). It looks like in your case you would want to pass the context as a parameter of readData() and writeData(). Or you could call getFilesDir() to get the storage directory and then pass that as the parameter to readData() and writeData().

    One other caveat (learned the hard way). Although undocumented, I've found that sometimes Android will create files in this application directory. I strongly recommend that rather than storing files directly in this application folder you instead create your own storage directory in the application directory returned by getFilesDir(), and then store your files there. That way you won't have to worry about other files that might show up, for example if you try to list the files in the storage directory.

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

    (I agree with P basak that DataInputStream and DataOutputStream are your best option for reading and writing the data. I disrecommend Serialization except in a very narrow set of applications where transportability is a factor as it is very inefficient. In my case objects that took 15 seconds to load via Serialization loaded in less than 2 seconds using DataInputStream.)

    0 讨论(0)
  • 2021-01-13 18:03

    For permission issues, I encourage you to use an external storage such as an SD card.

    Environment.getExternalStorageDirectory()
    

    you can create a folder there and save your files. You can also use "/data/local/" if your system permits user files to be saved there. You can refer to this page regarding the various ways you can save files to internal and external storage,

    For the second problem I suggest you to use 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();
    

    You can code something like this,

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

    You can also Use Serializable interface for reading and writing serializable objects. In fact, I used this once when I tried to write data values directly to files instead of any traditional databases (In my very first undergraduate years, I was not familiar with databases). A good example is here,

    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's 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())
      ;
    } 
    
    0 讨论(0)
  • 2021-01-13 18:04

    From what I see, you are trying to dump the contents of the object into a file and then read it back. But the way you are doing it now is just writing all the data to the file without any structure, which is a terrible idea.

    I would recommend you try to implement the Serializable interface and then just use the writeObject() and readObject() methods.

    Alternatively, you could dump the data into an XML file or something that has some structure to it.

    0 讨论(0)
提交回复
热议问题