保存在Java
接收到的数据我有发送bmp文件和客户端在Android中,我尝试保存我接收到的数据服务器。保存在Java
...
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();
}
}
但在输出I接收对象ID
例如: 我使用以下代码保存在一个文件中的数据 [B @ 23fgfgre [B @ eft908eh ...
(其中[装置array.The乙装置byte.The @分离从ID.The十六进制数字的类型是对象ID或哈希码。)
我甚至接收使用,而不是“为PrintWriter”“为PrintStream”同样的结果...
如何节省实际输出?
在PrintWriter
和PrintStream
名字应该给你一个暗示,它们所产生的文本单词“打印”。如果你仔细阅读了文档,那里就明确说明了。
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#print(java.lang.Object)
Specfically,为PrintWriter
的print(Object obj)
超载您正在使用的文件明确表示,
打印的对象。由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();
我用它,但该文件获取几秒钟太大......据java的手动写():将b.length个从指定的字节数组写入此文件输出流的字节。 –
我不明白为什么会发生这种情况...... –
这是一个完全不同的问题。我们不知道您如何使用此代码,您从何处获取数据,数据以何种速率进入等等。发布一个新问题,并附上http://*.com/help/mcve AND样本输入数据,并查看您是否得到该问题的答案。 –
尝试:
FileOutputStream f = new FileOutputStream(file, true);
f.write(inputMsg);
f.close();
您是否尝试过使用'write(byte [])'方法创建'FileOutputStream'中的'BufferedOutputStream'? –
'Rbuffer =新字节[2000];'。你的bmp文件是否小于2000字节? – greenapps
'dir.mkdirs();'。检查返回值。这可能是错误的。不要继续你的代码,如果它是假的,但显示敬酒和返回。 – greenapps