I have an xml file in my Android project.
It contains a simple list of employee ids.
I want to read the below xml content.
I placed this file in res/raw/
saplist.xml
<?xml version="1.0" encoding="UTF-8"?>
<EMPNOLIST>
<EMPID>“12345”</EMPID>
<EMPID>“23456”</EMPID>
<EMPID>“34567”</EMPID>
</EMPNOLIST>
Code to read it
{
// Load XML for parsing.
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("saplist.xml");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
String s = readTextFile(inputStream);
Log.e("FMApp: ", s);
}
private String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
This code doesn't read the xml content.
Instead, it crashes.
Could someone help me on how to read such a simple xml?
You can check http://developer.android.com/training/basics/network-ops/xml.html to read xml data.
You first closed the outputStream and then returned outputStream.toString() that isn't going to work.
private String readTextFile(InputStream inputStream) {
String result = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
result = outputStream.toString()
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return result;
}
Related
I have tried to use code below in my application to encode a jpg file to Base64.
InputStream inputStream = null;
try {
inputStream = new FileInputStream(imagelocation);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
Log.d(TAG, encodedString);
Output is following:
/9j/4Tj5RXhpZgAASUkqAAgAAAAPAA4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POWFf
M4+t7XEO2y0R91kmBeHy+N95av57fhYn/taFh5bQsPckU19ZtowxWNm9MmvKnax7SoSbsiJ9eXaG
ETdepIql488Z6b8Mfhlr3xm8cpcaf4Z8M6TcanrWqywEJBbQoXdhnG44BwoOWJAHWvNnSq4ifLTT
b8grKlhoc9WSS8z+dD9tux+Ff/BRr9sfxj+1H4e+HmqeFNP1NbdzpsVws8srIChu7jahEbSHBZV+
VcgAkjNdFrn/AAQm8HeK/wBleP8AaL/Z/wDjV4q8VaxN4w0fQT4NPhgW+Wu8efJPcxySC2hRUlJn
kUR5KFmUPgfoeDjVwWDp0pa8qSZ+V5jiYY7HTqxVk3p+Rx5/4IcfHzxDr+veD9U+Et94CXQfC0vi
G51u81631S3uIEuba1W2SS3GyOV3uVZVdwzLG+AcHHh3xL/4Jy6/8O7hre4+I87gAhwbIk5HU8Ng
iun6171rXOJw0uea6z+zPNpn7xvHhlV32xO1kRuHGercdf5diDXOXfwa1K3n8pPEUTgtjd5DA/kT
/wDq71rGqpENMif4TanFIIR4kt1kORtaNwDj39c1Xb4cazGmY/EVs+cDAL8nuM47etUqibFuA+G3
iYweemr2zKTtOZHz3wOlRDwB4rdxHFdwMd2B++Pb04qudN2BnU/CrW/j18F/EMvi/wCFfjmLR9Qe
OOOW5hdHMsaTxzKrK8bKyebDExUgg7QGBBwfYLX/AIKE/wDBSuzht7KL9
Already tried to put this code into several decoders, but cannot convert this code back to a picture. What should be the problem?
I'm new at android development and I'm creating simple bluetooth app that can receive xml file and save xml file values to database. But how can I receive xml file from bytes array? Is it possible? After searchinf I found this question and based ont that question I try to save byte array to file. But how I need to test it? I can't find my file in my phone.
case Constants.MESSAGE_READ:
byte[] readBuffer = (byte[]) msg.obj;
try {
String path = activity.getFilesDir() + "/myFile.xml";
Log.d("MuTestClass", path);
FileOutputStream stream = new FileOutputStream(path);
stream.write(readBuffer);
stream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
break;
You can use:
class Utils{
public static InputStream openFile(String filename) throws IOException{
AssetManager assManager = getApplicationContext().getAssets();
InputStream is = null;
is = assManager.open(filename);
return new BufferedInputStream(is);
}
public static byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}
like this:
try {
Utils.readBytes(Utils.openFile("something.xml"));
} catch (IOException e) {
e.printStackTrace();
}
I'm hitting an URL and saving the returned image response in cache dir. If I try to save Bitmap from Returned response inputstream then I get correct Bitmap. Now after saving that response inputstream in cache and after fetching it I'm getting null Bitmap
Write inputStream to cache dir -
String root = mContext.getCacheDir().toString();
String path = root + "/tomorrow.jpg";
try {
final File file = new File(path);
final OutputStream output = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) != -1)
output.write(buffer, 0, ch);
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
now I'm reading the file from cache dir -
FileInputStream fin = null;
try {
fin = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp1 = BitmapFactory.decodeStream(fin);
I'd like to thanks Dimitri Budiansky for guiding me. Fix as below-
//final byte[] buffer = new byte[1024];
//int ch;
//while ((ch = in.read(buffer)) != -1)
//output.write(buffer, 0, ch);
I commented above lines. Simply add below line.
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
for clarification u may check this Link
I want to copy zip file that includes images from asset to internal storage,And then unzip it.
This is my code :
protected void copyFromAssetsToInternalStorage(String filename){
AssetManager assetManager = getAssets();
try {
InputStream input = assetManager.open(filename);
OutputStream output = openFileOutput(filename, Context.MODE_PRIVATE);
copyFile(input, output);
} catch (IOException e) {
e.printStackTrace();
}
}
private void unZipFile(String filename){
try {
ZipInputStream zipInputStream = new ZipInputStream(openFileInput(filename));
ZipEntry zipEntry;
while((zipEntry = zipInputStream.getNextEntry()) != null){
FileOutputStream zipOutputStream = openFileOutput(zipEntry.getName(), MODE_PRIVATE);
int length;
byte[] buffer = new byte[1024];
while((length = zipInputStream.read(buffer)) > 0){
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.close();
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
And i have this error :
java.lang.IllegalArgumentException: File filename/ contains a path separator
What should i do?
From openFileOutput documentation:
name The name of the file to open; can not contain path separators.
Hope this helps
Yaron
This is my code for Reading .bin file. name:Testfile.bin location : Assets
In the byteRead(pathtobinfile) function I want to pass bin file path as a String.
how to get the bin file path. Any idea please!!!
public byte[] byteRead(String aInputFileName)
{
File file = new File(aInputFileName);
byte[] result = new byte[(int)file.length()];
try {
InputStream input = null;
try {
int totalBytesRead = 0;
input = new BufferedInputStream(new FileInputStream(file));
while(totalBytesRead < result.length){
int bytesRemaining = result.length - totalBytesRead;
//input.read() returns -1, 0, or more :
int bytesRead = input.read(result, totalBytesRead, bytesRemaining);
if (bytesRead > 0){
totalBytesRead = totalBytesRead + bytesRead;
}
}
}
finally {
//log("Closing input stream.");
input.close();
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
Log.d("File Length", "Total No of bytes"+ result.length);
return result;
}
Any help?
Implement following code, which I modified as per your requirement. I have tested it and working very well.
public byte[] byteRead(String aInputFileName) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
InputStream input = getResources().getAssets().open(aInputFileName);
try {
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1) {
baos.write(buffer, 0, read);
}
} finally {
input.close();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
Log.d("Home", "Total No of bytes : " + baos.size());
return baos.toByteArray();
}
Input
You can use this function like this.
byte[] b = byteRead("myfile.txt");
String str = new String(b);
Log.d("Home", str);
Output
09-16 12:25:34.340: DEBUG/Home(4552): Total No of bytes : 10
09-16 12:25:34.340: DEBUG/Home(4552): hi Chintan
Its a very easy to read bin file from Asset folder.
Hope this will help someone.
InputStream input = context.getAssets().open("Testfile.bin");
// myData.txt can't be more than 2 gigs.
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();