我想从互联网上拿xml,但每次从网上拿xml对我的应用程序来说都很慢,所以我想把它保存在本地目录中,下次我打开应用程序然后在后端再次从互联网上复制xml到我的xml
怎么做,有没有其他好办法解决这个问题?
答案 0 :(得分:1)
请使用以下功能将文件写入SD卡。
private static String APP_DOC_DIR = "file:///SDCard/BlackBerry/documents/MyAPP/";
public static void writeToSD(String fileName, String fileContent){
FileConnection fconn = null;
// APP_DOC_DIR is the directory name constant.
try {
FileConnection fc = (FileConnection)Connector.open(APP_DOC_DIR);
// If no exception is thrown, the URI is valid but the folder may not exist.
if (!fc.exists())
{
fc.mkdir(); // create the folder if it doesn't exist
}
fc.close();
fconn = (FileConnection) Connector.open(APP_DOC_DIR + fileName ,Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
}
fconn.setReadable(true);
fconn.setWritable(true);
OutputStream os = fconn.openOutputStream();
os.write(fileContent.getBytes("UTF8"));
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fconn!=null) {
try {
fconn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
从SD卡读取文件如下。
public static String readFromSD(String fileName)
{
String resultString = "";
int BUFFER_SIZE = 10000;
InputStream inputStream = null;
FileConnection fconn;
try {
fconn = (FileConnection) Connector.open( APP_DOC_DIR + fileName, Connector.READ);
if (fconn.exists())
{
inputStream = fconn.openInputStream();
}
else
{
return "";
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
int bytesRead = inputStream.read( buffer, 0, BUFFER_SIZE );
if (bytesRead == -1)
break;
byteArrayOutputStream.write( buffer, 0, bytesRead );
}
byteArrayOutputStream.flush();
byte[] result = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
//resultString = new String(result,"UTF8");
resultString = new String(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultString;
}