对于我的android应用程序,我需要从url下载JSON到android的内部存储,然后从中读取。我认为将其另存为byte []到内部存储中的最佳方法,尽管我在这里遇到了一些问题,但这是我到目前为止编写的
File storage = new File("/sdcard/appData/photos");
storage.mkdirs();
JSONParser jParser = new JSONParser();
// getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url1);
//transforming jsonObject to byte[] and store it
String jsonString = json.toString();
byte[] jsonArray = jsonString.getBytes();
String filen = "jsonData";
File fileToSaveJson = new File("/sdcard/appData",filen);
FileOutputStream fos;
fos = new FileOutputStream(fileToSaveJson);
fos = openFileOutput(filen,Context.MODE_PRIVATE);
fos.write(jsonArray);
fos.close();
//reading jsonString from storage and transform it into jsonObject
FileInputStream fis;
File readFromJson = new File("/sdcard/appData/jsonData");
fis = new FileInputStream(readFromJson);
fis = new FileInputStream(readFromJson);
InputStreamReader isr = new InputStreamReader(fis);
fis.read(new byte[(int)readFromJson.length()]);
但它不会打开文件以进行读取
最佳答案
public static File createCacheFile(Context context, String fileName, String json) {
File cacheFile = new File(context.getFilesDir(), fileName);
try {
FileWriter fw = new FileWriter(cacheFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(json);
bw.close();
} catch (IOException e) {
e.printStackTrace();
// on exception null will be returned
cacheFile = null;
}
return cacheFile;
}
public static String readFile(File file) {
String fileContent = "";
try {
String currentLine;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((currentLine = br.readLine()) != null) {
fileContent += currentLine + '\n';
}
br.close();
} catch (IOException e) {
e.printStackTrace();
// on exception null will be returned
fileContent = null;
}
return fileContent;
}
关于java - 从内部存储中的url保存JSON文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19315316/