我有服务器在Android中发送bmp文件和客户端,我尝试保存我收到的数据。 我使用以下代码将数据保存在文件中:
...
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();
}
}
但是在输出中我收到了对象ids
e.g。 [B @ 23fgfgre [B @ eft908eh ...
(其中[表示数组.B表示字节。@将类型与ID分开。十六进制数字是对象ID或哈希码。)
即使使用" PrintStream"我也会收到同样的结果。而不是" PrintWriter" ...
如何保存实际输出?
答案 0 :(得分:2)
尝试:
FileOutputStream f = new FileOutputStream(file, true);
f.write(inputMsg);
f.close();
答案 1 :(得分:1)
PrintWriter
和PrintStream
名称中的“print”一词应该会提示您生成文本。如果你仔细阅读文档,那就明确说明了。
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#print(java.lang.Object)
具体而言,您明确使用的print(Object obj)
PrintWriter
重载文档
打印一个对象。 String.valueOf(Object)方法生成的字符串根据平台的默认字符编码转换为字节,这些字节的写入方式与write(int)方法完全相同。
显然,这不是你想要的。您有一个字节数组,并且您希望将这些字节写入文件,就像它们一样。所以,忘掉PrintWriter
和PrintStream
。相反,做这样的事情:
BufferedOutputStream bos = new BufferedOutputStream(f);
bos.write(inputMsg);
//bos.flush(); stop. always. flushing. close. does. that.
bos.close();