Escribir archivo .json y leer ese archivo en Android
Im archivo de escritura .json y quiero leer ese archivo, pero el problema es, cuando intento leer el archivo entero como cadena que agrega el espacio antes y después de cada carácter y sólo porque de caracteres adicionales que no podía leer json.
El formato Json es
- ¿Cómo se puede convertir mejor StringBuilder en String ?
- Comprobando si existe subobjeto en JSON
- Margen ajustado a la primera línea de textView
- Android: evita romper la línea en las partes TextView String
- ¿Cómo comprobar el idioma de un dispositivo en android?
[{"description1":"The ThinkerA bronze sculpture by Auguste Rodin. It depicts a man in sober\nmeditation battling with a powerful internal struggle.","description2":"Steve JobsFounder of Apple, he is widely recognized as a charismatic pioneer of\nthe personal computer revolution.","description3":"Justin BieberBorn in 1994, the latest sensation in music industry with numerous\nawards in recent years."}]
Pero da una respuesta weired como: [{"description 1": "T …..
Para recortar los espacios extra que se refieren a esto, pero stil didnt trabajo: Java cómo reemplazar 2 o más espacios con un solo espacio en la cadena y eliminar los espacios principales sólo
Estoy usando este codigo
File folderPath = Environment.getExternalStorageDirectory(); File mypath=new File(folderPath, "description.json"); StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = null; reader = new BufferedReader(new FileReader(mypath)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } String response = fileData.toString();
La cadena de "respuesta" contiene respuesta extraña
Así que ¿alguien puede ayudarme?
Para escribir en archivo, im usando:
FileOutputStream fos = new FileOutputStream(mypath); DataOutputStream dos = new DataOutputStream(fos); dos.writeChars(response);
- String-arrays de referencia en android strings.xml
- Android StringBuilder vs Concatenación de cadenas
- Alternativa de DatatypeConverter.printHexBinary (byte array) y DatatypeConverter.parseHexBinary (String str) en Android
- Quiero dividir mi cadena con los siguientes símbolos: +, -, *, / pero la función .split sólo acepta una
- Excepción OutOfMemory en la conversión de ByteArray a String?
- Donde usar StringBuffer / StringBuilder que String
- Ellipsize sólo una sección en un TextView
- Byte array -> String -> Conjunto de bytes
WriteChars escribe cada carácter como dos bytes.
http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChars(java.lang.String )
http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChar(int )
Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2.
Escriba a continuación el método para escribir el archivo Json, Aquí params
es un nombre de archivo y mJsonResponse
es una respuesta del servidor.
Para crear archivos en la memoria interna de la aplicación
public void mCreateAndSaveFile(String params, String mJsonResponse) { try { FileWriter file = new FileWriter("/data/data/" + getApplicationContext().getPackageName() + "/" + params); file.write(mJsonResponse); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } }
Para leer datos del archivo Json, Aquí params
es File Name.
public void mReadJsonData(String params) { try { File f = new File("/data/data/" + getPackageName() + "/" + params); FileInputStream is = new FileInputStream(f); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String mResponse = new String(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Me gusta arriba de la respuesta y editado: Me encanta compartir, así que he compartido que puede ser útil a los demás.
Copie y pegue la siguiente clase en su paquete y use como:
Guardar: MyJSON.saveData(context, jsonData);
Leer: String json = MyJSON.getData(context);
import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; /** * Created by Pratik. */ public class MyJSON { static String fileName = "myBlog.json"; public static void saveData(Context context, String mJsonResponse) { try { FileWriter file = new FileWriter(context.getFilesDir().getPath() + "/" + fileName); file.write(mJsonResponse); file.flush(); file.close(); } catch (IOException e) { Log.e("TAG", "Error in Writing: " + e.getLocalizedMessage()); } } public static String getData(Context context) { try { File f = new File(context.getFilesDir().getPath() + "/" + fileName); //check whether file exists FileInputStream is = new FileInputStream(f); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); return new String(buffer); } catch (IOException e) { Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage()); return null; } } }
Su código de escritura es el problema. Solo usa
FileWriter fos = new FileWriter(mypath); fos.write(response);
- ¿Es posible crear una matriz de mapa de bits en android
- Permisos del administrador de ubicaciones de Android que se utilizarán