我創建了一個類型爲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();
}
}
}
任何幫助將不勝感激。
我喜歡使用Serializable接口的想法。但我寧願將它保存在內部存儲器中。有沒有辦法繞過拒絕的權限? – miszu
正如我前面提到的,您可以在用戶模式下訪問的大部分時間保存在/ data/local中。如果您想要自定義目錄,則必須對電話進行根目錄更改目錄的權限。否則你必須使用分配給應用程序的數據區域。 http://developer.android.com/training/basics/data-storage/files.html 以及http://developer.android.com/training/basics/data-storage/index.html –