How to get a json file from raw folder? - android

I want to use my user.json which is in my raw folder to get a new File :
// read from file, convert it to user class
User user = mapper.readValue(new File(**R.raw.user**), User.class);
I found that InputStream can do it :
InputStream ins = res.openRawResource(
getResources().getIdentifier("raw/user",
"raw", getPackageName()));
Is there a better way to do it, directly with my json file ID ?

InputStream is = getResources().openRawResource(R.raw.json_file);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String jsonString = writer.toString();

ObjectMapper.readValue also take InputStream as source . Get InputStream using openRawResource method from json file and pass it to readValue :
InputStream in = getResources().openRawResource(R.raw.user);
User user = mapper.readValue(in, User.class);

Kotlin way :
val raw = resources.openRawResource(R.raw.posts)
val writer: Writer = StringWriter()
val buffer = CharArray(1024)
raw.use { rawData ->
val reader: Reader = BufferedReader(InputStreamReader(rawData, "UTF-8"))
var n: Int
while (reader.read(buffer).also { n = it } != -1) {
writer.write(buffer, 0, n)
}
}
val jsonString = writer.toString()

Related

FileInputStream to Json in Xamarin Android

I have a FileInputStream which is coming in from an Android Intent
var parcelFileDescriptor = this.ContentResolver.OpenFileDescriptor(extras, "r");
var fileInputStream = new FileInputStream(parcelFileDescriptor.FileDescriptor);
I know the resulting file is a json file, how do I go from FileInputStream to Json? I assume I need to go from FileInputStream to Stream and then to Json but not sure how to do that
Thanks
How I ended up solving it
var parcelFileDescriptor = this.ContentResolver.OpenFileDescriptor(extras, "r");
var fileInputStream = new FileInputStream(parcelFileDescriptor.FileDescriptor);
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
int n;
while ((n = fileInputStream.Read(buffer)) != -1)
{
fileContent.Append(new String(buffer, 0, n));
}
var result = Newtonsoft.Json.JsonConvert.DeserializeObject(fileContent.ToString());

Correct file path of assets android

I'm trying to access the file path of my assets folder but for some reason, I can't access it and it creates an error(Unable to start activity ComponentInfo, Host name may not be null). What should be the correct syntax for this?
This is my code:
String xml = parser.getXmlFromUrl("file:///android_assets/music.xml");
and this is my file location:
Am I doing it properly? Or is my syntax incorrect?
try this, open an input stream on that file.
InputStreamReader is= new InputStreamReader(
context.getAssets().open("abc.xml"));
and then open and then
int length = is.available();
byte[] data = new byte[length];
is.read(data);
String xmlString = new String(data);
Hope It will help
Maybe
AssetManager assetManager = getAssets();
InputStream input = assetManager.open(fileName);
And after read file?
try using by filedescriptor as
AssetFileDescriptor descriptor = getAssets().openFd("myfile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());
Please use this code, its working code for text file as well as xml file.
public String readFromAssetsFolder(String fileName) {
String readValue = "";
InputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader input = null;
try {
fileInputStream = getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
inputStreamReader = new InputStreamReader(fileInputStream);
input = new BufferedReader(inputStreamReader);
String line = "";
while ((line = input.readLine()) != null) {
readValue = readValue+ line;
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (inputStreamReader != null)
inputStreamReader.close();
if (fileInputStream != null)
fileInputStream.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return readValue;
}

Load local HTML file(from assets) to a String

How can I load a local html file(from assets folder) to a String?
I tried this code but the result is only "?????...".
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
System.out.println(str);
thanks for any help!
You are not reading the whole file. Try this:
StringBuilder builder = new StringBuilder();
byte[] buffer = new byte[1024];
while(is.read(buffer) != -1) {
builder.append(new String(buffer));
}
is.close();
String str = builder.toString();
try this......
File file = new File("file:///android_asset/yuor_file.html");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String linewise = br.readLine();
while(linewise != null) {
sb.append(linewise );
sb.append("\n");
linewise = br.readLine();
}
//now data in sb

Android write to file

I've made I simple function to write from URL to file. Everything works good until out.write(), I mean there's no exception, but it just doesn't write anything to file
Here's code
private boolean getText(String url, String name) throws IOException {
if(url!=null){
FileWriter fstream = new FileWriter(PATH+"/"+name+".txt");
BufferedWriter out = new BufferedWriter(fstream);
URL _url = new URL(url);
int code = ((HttpURLConnection) _url.openConnection()).getResponseCode();
if(code==200){
URLConnection urlConnection = _url.openConnection(); //
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) != -1) {
String chunk = new String(buffer, 0, bytesRead);
out.write(chunk);
}
return true;
}
out.close();
}
return false;
}
Can someone tell me what's wrong please?
Try fstream.flush().
Also out.close() should be called before returning from a function.

Read/write file to internal private storage

I'm porting the application from Symbian/iPhone to Android, part of which is saving some data into file. I used the FileOutputStream to save the file into private folder /data/data/package_name/files:
FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE );
fos.write( data.getBytes() );
fos.close();
Now I am looking for a way how to load them. I am using the FileInputStream, but it allows me to read the file byte by byte, which is pretty inefficient:
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = iContext.openFileInput( IDS_LIST_FILE_NAME );
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
String data = new String(fileContent);
So my question is how to read the file using better way?
Using FileInputStream.read(byte[]) you can read much more efficiently.
In general you don't want to be reading arbitrary-sized files into memory.
Most parsers will take an InputStream. Perhaps you could let us know how you're using the file and we could suggest a better fit.
Here is how you use the byte buffer version of read():
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fileContent.append(new String(buffer));
}
This isn't really Android-specific but more Java oriented.
If you prefer line-oriented reading instead, you could wrap the FileInputStream in an InputStreamReader which you can then pass to a BufferedReader. The BufferedReader instance has a readLine() method you can use to read line by line.
InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine()
Alternatively, if you use the Google Guava library you can use the convenience function in ByteStreams:
String data = new String(ByteStreams.toByteArray(fis));
//to write
String data = "Hello World";
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME,
Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
//to read
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
context.getFilesDir() returns File object of the directory where context.openFileOutput() did the file writing.

Categories

Resources