java - 在 Android 中写入和读取二进制文件

标签 java android fileinputstream fileoutputstream

我创建了一个类型为 Task 的自定义对象,我想将它保存在内部存储中的二进制文件中。这是我创建的类:

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;

    }
}

在一个 Activity 中,我创建了一个将我的对象保存到文件的方法。这是我使用的代码:

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

现在我想创建一个方法来从文件中提取数据。通过在 Internet 上阅读,很多人使用 FileInputStream 但我无法从中提取字节并知道 String 可以有多长。此外,我使用了一种在网上找到的简单方法,但我的权限被拒绝了。正如我所说,我是 Android 开发的新手。

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

我们将不胜感激。

最佳答案

对于权限问题,我建议您使用外部存储,例如 SD 卡。

Environment.getExternalStorageDirectory()

您可以在那里创建一个文件夹并保存您的文件。如果您的系统允许将用户文件保存在那里,您也可以使用“/data/local/”。 可以引用这个page关于将文件保存到内部和外部存储的各种方式,

对于第二个问题我建议你使用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用于读取和写入可序列化对象的接口(interface)。事实上,当我试图将数据值直接写入文件而不是任何传统数据库时,我曾使用过一次(在我本科的第一年,我不熟悉数据库)。一个很好的例子是 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())
  ;
} 

关于java - 在 Android 中写入和读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21816049/

相关文章:

android - 无法删除 Activity 中的标题栏

java - 输入流的skip方法总是返回0

java - 创建流时是否应该显式创建文件?

java - 如何将 solr 与 Dismal RequestHandler 一起使用?

Java Spring - 仅保存(POST)来自 ManyToOne 关系的 id

java - Map 的 keySet() 和 entrySet() 的性能注意事项

java - 如何声明变量

java - Java Servlet Google App Engine 中的编码

android - AsyncTask中如何处理isCancelled

java - 如何对使用 Scanner 和 InputStream 的方法进行单元测试?