2014-02-16 164 views
3

我創建了一個類型爲Task的自定義對象,我想將它保存在內部存儲器中的二進制文件中。下面是我創建的類:在android中讀取二進制文件

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; 

} 
} 

在活動中,我創建了一個將我的對象保存到文件的方法。這是我使用的代碼:

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

     } 
} 

現在我想創建一個方法,將從文件中提取數據。通過在互聯網上閱讀,很多人使用FileInputStream,但我無法從中提取字節並知道字符串可以多長時間。此外,我使用了一種簡單的在線方法,但是我拒絕了權限。正如我所說,我對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(); 
     } 
    } 
} 

任何幫助將不勝感激。

回答

7

對於許可問題,我鼓勵您使用外部存儲,如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接口讀取和寫入可序列化的對象。事實上,當我試圖將數據值直接寫入文件而不是任何傳統數據庫時,我曾經使用過這一次(在我第一次大學時,我對數據庫並不熟悉)。一個很好的例子是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

我喜歡使用Serializable接口的想法。但我寧願將它保存在內部存儲器中。有沒有辦法繞過拒絕的權限? – miszu

+0

正如我前面提到的,您可以在用戶模式下訪問的大部分時間保存在/ data/local中。如果您想要自定義目錄,則必須對電話進行根目錄更改目錄的權限。否則你必須使用分配給應用程序的數據區域。 http://developer.android.com/training/basics/data-storage/files.html 以及http://developer.android.com/training/basics/data-storage/index.html –

0

從我所看到的,你正試圖將對象的內容轉儲到一個文件,然後讀回。但是你現在所做的只是將所有數據寫入文件而沒有任何結構,這是一個可怕的想法。

我會建議您嘗試執行Serializable interface,然後使用writeObject()和readObject()方法。

或者,您可以將數據轉儲到XML文件或具有某種結構的東西。

0

Android爲每種應用程序提供一個專用的目錄結構,以確切地處理這類數據。你不需要特殊的權限來訪問它。唯一的警告(這通常是一個很好的警告)是只有您的應用程序可以訪問它。 (這個原則是安全性的一部分,可以防止其他應用程序對您造成不良影響。)

如果遇到您需要的存儲空間,只需從任何可用的上下文(通常是您的活動)調用getFilesDir()即可。它看起來像你的情況,你會想要通過作爲readData()writeData()參數的上下文。或者您可以撥打getFilesDir()來獲取存儲目錄,然後將其作爲參數傳遞給readData()writeData()

另外一個警告(學習困難的方式)。雖然沒有記錄,但我發現有時Android會在這個應用程序目錄中創建文件。我強烈建議您不要直接在此應用程序文件夾中存儲文件,而應在getFilesDir()返回的應用程序目錄中創建自己的存儲目錄,然後將文件存儲在那裏。這樣,您就不必擔心可能出現的其他文件,例如,如果您嘗試列出存儲目錄中的文件。

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

(我有P basak同意DataInputStreamDataOutputStream用於讀取和寫入數據最好的選擇。我disrecommend序列化,除了在非常狹窄的一些應用中可運輸是一個因素,因爲它是非常低效的。在我的情況下,需要15秒才能通過序列化加載的對象使用DataInputStream在不到2秒內加載。)