我正在将文件读取到块中的字节数组中,并通过POST请求将其发送到网络服务器。这并不复杂,我在使用完全相同的代码之前完成了它。这一次,我注意到当我的图像到达服务器时看起来很奇怪,所以我决定查看正在发送的字节数组和正在接收的字节数组,以确保它们是相同的。不是。在java发送端,字节数组包含负数。在C#接收方,没有负数。Java字节数组包含负数
在接收侧的前15个字节(C#)
137
80
78
71
13
10
26
10
0
0
0
13
73
72
68
那些相同字节,但在发送侧(JAVA)
-119
80
78
71
13
10
26
10
0
0
0
13
73
72
68
所有非负数的是相同的,-119不是唯一的负数,他们都结束了。我确实注意到-119和137相距256,并想知道这是否与它有关。
我使用读取图像的代码(JAVA)
public static byte[] readPart(String fileName, long offset, int length) throws FileNotFoundException, Exception
{
byte[] data = new byte[length];
File file = new File(fileName);
InputStream is = new FileInputStream(file);
is.skip(offset);
is.read(data,0,data.length);
is.close();
return data;
}
我用写数据的代码(C#)
private void writeFile(string fileName, Stream contents)
{
using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = contents.Read(buffer, 0, bufferLen)) > 0)
{
fs.Write(buffer, 0, count);
}
fs.Close();
}
contents.Close();
}
我不知道这是总是发生的事情,我从来没有注意到它,或者如果它决定发生可怕的错误。我所知道的是,此代码之前的工作非常类似,并且现在不工作。
如果有人有任何建议或解释我会很感激。
编辑: 我的图像看起来很奇怪的原因是我如何调用readPart方法。
byte[] data = FileUtilities.readPart(fileName,counter,maxFileSize);//counter is the current chunk number
如何,我会一直称这是
byte[] data = FileUtilities.readPart(fileName,counter*maxFileSize,maxFileSize);//the current chunk * cuhnksize for the offset...
谢谢大家,我现在显著少困惑:)
刚刚尝试使用数据[i] =(byte)Math.abs((int)data [i])发送所有字节之前,这不起作用,它告诉我图像在那时已经腐败了。 – nick 2012-03-07 21:35:28
它只是整个文件的第一个字节,还是每个块的第一个字节? – 2012-03-07 21:37:37
Java的'byte'是有符号的,所以不可能有137个字节存储在'byte'中。也许你的问题来自这个? – Laf 2012-03-07 21:37:45