FileInputStream to Json in Xamarin Android - 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());

Related

Is there a way to convert audio files to byte array in android studio

I'm trying to store an audio file that is picked by the user from his own music player into sqlite database and I want to know is there a way to convert audio files to byte array.
String path = ""; // Audio File path
InputStream inputStream = new FileInputStream(path);
byte[] arr = readByte(inputStream);
Log.d("byte: ", "" + Arrays.toString(arr));
or
public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
os.write(buffer, 0, len);
}
return os.toByteArray();
}
try {
String path = ""; // Audio File path
InputStream inputStream = new FileInputStream(path);
byte[] myByteArray = getBytesFromInputStream(inputStream);
// ...
} catch(IOException e) {
// Handle error...
}

How to get a json file from raw folder?

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()

File not saved using FileOutputStream and InputStream

I'm getting data from an api and I want to write/save some file with that data. This is my code
try
{
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/incubate_files");
if (!myDir.exists()) myDir.mkdirs();
File file = new File(Environment.getExternalStorageDirectory().getPath()+File.separator+"/incubate_files/", "messageId_"+messageId+"."+ext);
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = content.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
output.close();
output.flush();
content.close();
}
catch (Exception e)
{
e.printStackTrace();
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
There is no exception, only a empty file
Thanks!
UPDATE
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
Log.d(app.TAG,"Cadena: "+builder.toString());
InputStream is = new ByteArrayInputStream(builder.toString().getBytes());
I change my InputStream white the content of the api. The api returns a lot of characters. The image actually exists in the server and I can see it.
Now the file is with some bytes but I cant see in my phone
The api reponse is in binary
You need to make use of getInputStream method from connection object and save the data into a File. For example:
InputStream input = connection.getInputStream();
File file = new File("download_directory_path", "file_name");
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = input.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
and then finally close() your output and input streams.
Once, writing is complete, the file points to the downloaded file.

Android : How to determine the file extension of a file

I am trying to share files between two Android phones using Socket programming. The problem is right now I have to hard code the file extension on the receiving end. Is there a way that I can automatically determine the extension of the file being received?
Here's my code.
Client Side
socket = new Socket(IP,4445);
File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
FileInputStream fis = null;
fis = new FileInputStream(myFile);
OutputStream os = null;
os = socket.getOutputStream();
int filesize = (int) myFile.length();
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
os.flush();
os.close();
fis.close();
socket.close();
}
And the Server side
FileOutputStream fos = null;
File root = Environment.getExternalStorageDirectory();
fos = new FileOutputStream(new File(root,"B.jpg")); //Here I have to hardcode B.jpg with jpg extension.
BufferedOutputStream bos = new BufferedOutputStream(fos);
ServerS = new ServerSocket(4445);
clientSocket = ServerS.accept();
InputStream is = null;
is = clientSocket.getInputStream();
int bytesRead = 0;
int current = 0;
byte [] mybytearray = new byte [329];
do {
bos.write(mybytearray,0,bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
} while(bytesRead > -1);
bos.flush();
bos.close();
clientSocket.close();
}
You can find the file extension pretty easily by doing this:
String extension = filename.substring(filename.lastIndexOf('.'));

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.

Categories

Resources