当前位置: 动力学知识库 > 问答 > 编程问答 >

save - android how to read data using internal storage

问题描述:

public void loadprev()

{

String tempread;

try {

FileInputStream fis = openFileInput("data.gds");

try {

fis.read(tempread.getBytes());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

fis.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

my program crashes upon trying to execute fis.read(tempread.getBytes());

i want to read the first line in data.gds and put it into a string, how can i do this?

and no, im not going to use SharedPreferences

网友答案:

add a string buffer and then read from it everyline will be put in the Stringbuffer, then you can retrieve the line from that buffer.

StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];

while ((n = fis.read(buffer)) != -1) 
{ 
  fileContent.append(new String(buffer, 0, n)); 
}

Also, if you are not catching exceptions properly, surround them in 1 try catch, but try to catch them in the future:

{
    String tempread;
 try {
    FileInputStream fis = openFileInput("data.gds");
        fis.read(tempread.getBytes());
        fis.close();
   } catch (FileNotFoundException e) {
        e.printStackTrace();
   }
     catch (IOException e) {
        e.printStackTrace();
       }

}

now your code is easier to read.

分享给朋友:
您可能感兴趣的文章:
随机阅读: