I have server that sends bmp file and a client in Android where I try to save the data that i received. I save the data in a file using the following code:
...
byte[] Rbuffer = new byte[2000];
dis.read(Rbuffer);
try {
writeSDCard.writeToSDFile(Rbuffer);
} catch (Exception e) {
Log.e("TCP", "S: Error at file write", e);
} finally {
Log.e("Writer", "S: Is it written?");
}
...
void writeToSDFile(byte[] inputMsg){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/download");
if (!(dir.exists())) {
dir.mkdirs();
}
Log.d("WriteSDCard", "Start writing");
File file = new File(dir, "myData.txt");
try {
// Start writing in the file without overwriting previous data ( true input)
Log.d("WriteSDCard", "Start writing 1");
FileOutputStream f = new FileOutputStream(file, true);
PrintWriter ps = new PrintWriter(f);
// PrintStream ps = new PrintStream(f);
ps.print(inputMsg);
ps.flush();
ps.close();
Log.d("WriteSDCard", "Start writing 2");
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
}
But in the output I receive the object ids
e.g. [B@23fgfgre[B@eft908eh ...
(Where [ means array.The B means byte.The @ separates the type from the ID.The hex digits are an object ID or hashcode.)
The same result i receive even using "PrintStream" instead of "PrintWriter"...
How can I save the real output?
The word "print" in the names of PrintWriter
and PrintStream
should give you a hint that they generate text. If you read the documentation thoroughly, that's explicitly stated in there.
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#print(java.lang.Object)
Specfically, the documentation for the print(Object obj)
overload of PrintWriter
that you are using explicitly says
Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
Clearly, that's not what you want. You have an array of bytes and you want to write those bytes into a file, exactly as they are. So, forget about PrintWriter
and PrintStream
. Instead, do something like this:
BufferedOutputStream bos = new BufferedOutputStream(f);
bos.write(inputMsg);
//bos.flush(); stop. always. flushing. close. does. that.
bos.close();