用java保存接收到的数据



我有发送bmp文件的服务器和Android客户端,我试图保存我收到的数据。我使用以下代码将数据保存在一个文件中:

...
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();
    }
}

但是在输出中我接收到对象id

。[B@23fgfgre [B@eft908eh…

(其中[表示数组。B表示字节。@将类型与ID分开。十六进制数字是对象ID或哈希码。)

即使使用"PrintStream"而不是"printwwriter",我也收到相同的结果…

如何保存实际输出?

尝试:

FileOutputStream f = new FileOutputStream(file, true);
f.write(inputMsg);
f.close();

PrintWriterPrintStream名称中的单词"print"应该提示您它们生成文本。如果你仔细阅读了文档,就会发现里面有明确的说明。

https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html打印(java . lang . object)

具体来说,您正在使用的PrintWriterprint(Object obj)过载的文档明确地说

打印对象。由string . valueof (Object)方法产生的字符串根据平台的默认字符编码被转换成字节,并且这些字节完全按照write(int)方法的方式写入。

很明显,那不是你想要的。你有一个字节数组,你想把这些字节原原本本地写进一个文件。所以,忘掉PrintWriterPrintStream吧。相反,可以这样做:

BufferedOutputStream bos = new BufferedOutputStream(f);
bos.write(inputMsg);
//bos.flush(); stop. always. flushing. close. does. that.
bos.close();

相关内容

  • 没有找到相关文章

最新更新