Android read write json

直接貼代碼了,這個是用google提供的json庫 gson 2.5 下載地址download

	private void loadData(){
		File fileDir = getFilesDir();
		String fileDirString = fileDir.getPath();
		String jsonFilePath = fileDirString + File.separator + FILE_NAME_JSON;
		
		File jsonFile = new File(jsonFilePath);
		if (jsonFile.exists() == false) {
			try {
				boolean bret = jsonFile.createNewFile();
				if (false == bret) {
					return;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
		}
			
		writeData(jsonFilePath);
		
		readData(jsonFilePath);		
	}
	
	private void writeData(final String jsonFilePath){
		
		JSONObject jsonObject = new JSONObject();
		
		try {
			jsonObject.put("id", "1222");
			jsonObject.put("name", "Mrs Joden.");
			jsonObject.put("phone", "224-33223624");
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		
		FileWriter fileWriter = null;
		
		try {
			fileWriter = new FileWriter(jsonFilePath);
			fileWriter.write(jsonObject.toString());
			fileWriter.flush();
		} catch (Exception e) {
			// TODO: handle exception
		}
		finally{
			if (null != fileWriter) {
				
				try {
					fileWriter.close();
					fileWriter = null;
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
	}
	
	private void readData(final String jsonFilePath){
		
		InputStream inputStream = null;
		String jsonString;
		
		try {
			
			inputStream = new FileInputStream(jsonFilePath);
			
			int size = inputStream.available();
			
			byte buffer[] = new byte[size];
			
			inputStream.read(buffer);
			
			jsonString = new String(buffer,"UTF-8");
			
		} catch (Exception e) {
			// TODO: handle exception
			return;
		}
		finally{
			if (null != inputStream) {
				try {
					inputStream.close();
					inputStream = null;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		String s = jsonString;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章