我的程序讀取一個文件爲字節數組,但是我不知道數組result中有多少負數。我認爲陣列中的元素的值在0到255範圍內。代碼在這裏:InputStream的read(byte [] b)返回一個字節數組有負值的元素
public static void main(String [] args)
{
try
{
File file = new File("C:\\1.mp3");
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fis.read(bytes);
boolean check = true;
int i = -1;
while(check)
{
i=i+1;
if(bytes[i]<0)
{
check = false;
System.out.println("There is a negative number.");
}
}
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}
}
感謝您的幫助。
Java字節的值在-128到127的範圍內。我不明白爲什麼這是一個問題。 – 2013-04-11 02:51:18
但是我讀了Java Document,我看到「從輸入流中讀取下一個字節的數據。值字節在0到255範圍內返回爲int」。我認爲0 <=數組元素<= 255。 – loithuxua 2013-04-11 02:59:13
這隻有在你使用int read()讀取一個字節時纔是真的。使用這個函數可以得到0到255的值,如果是-1您已到達流的末尾。 – 2013-04-11 07:35:15