2012-10-10 74 views
1

我正在写一个应用程序,它必须通过蓝牙发送一些文件。 客户端收到一个字节数组,它必须被构建到文件中。但是只有几行数组被复制到文件中! 这里是我的线程代码,其中来自服务器的每条消息都被读取:从android中byte []写入文件失败

编辑:try/catch代码。

try { 
    FileOutputStream fos = new FileOutputStream("//mnt//sdcard//" + fileName);  
    fos.write(buffer); 
    fos.close(); 
} 
catch(FileNotFoundException e) { 
    Log.d("FAIL", e.toString()); 
    } 
catch (IOException e) { 
    Log.d("FAIL", e.toString()); 
} 

缓冲区是byte []。我甚至用Toast进行了检查:缓冲区一切正常。它包含来自文件的每个符号,但我无法以某种方式写出它。

+0

能否详细说明'不能写'?你有错误吗?它是否创建一个0byte文件?或无? – dispake

+0

你确定你正在'buffer'中接收整个文件吗? – m0skit0

+0

如果出现问题,创建,写入和关闭'fos'应该抛出异常。用try/catch块封装你的代码,让我们知道它捕获了什么样的异常。 – Dylan

回答

1

,你可以尝试使用的一个例子是:

FileOutputStream outputStream = new FileOutputStream(new File(context.getCacheDir(), FILENAME), false); 
OutputStream out = new BufferedOutputStream(outputStream); 
byte[] loginBuffer = new byte[1024]; 
int byteRead = 0; 
while((byteRead = in.read(loginBuffer)) != -1) { 
    out.write(loginBuffer, 0, byteRead); 
} 
out.close(); 
0

特里告诉你多么想在文件上写

fos.write(缓冲,0,X);

其中x是以字节为单位 缓冲区的大小和0偏移

2

应将文件路径是你一个人从来没有硬编码。

在Android中,你应该使用Environment.getExternalStorageDirectory

String fname = Environment.getExternalStorageDirectory() + "myfile.jpg"; 
File file = new File(fname); 

如果你没有在文件路径指定Environment.getExternalStorageDirectory,它会在你的应用程序安装文件夹的回报。

在你的情况,该文件可能已被写入“com.your.package/test.jpg放在”

+0

嗯,那只是一个测试。文件被写入正确的地方它应该写(它位于我的SD卡上),所以问题不存在 –

0

我认为最有可能的罪魁祸首是你的应用程序没有写权限。

https://sites.google.com/site/androidhowto/how-to-1/save-file-to-sd-card

您需要添加以下到AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

注意:你得到一个FileNotFoundException如果你试图打开/上创建文件安装在计算机上的SD卡。您必须先卸载它,然后才能在应用程序中访问它。

+0

不幸的是,这并没有解决我的问题。 权限是可以的,找到并成功创建了文件,但其中只有一部分被写入(例如3.6kb的2.4) –