-1

So I have a value FFD8FFE0 (jpg/jpeg signature) and I want to check is the uploaded file is jpg/jpeg, but it returns false

val param = new FileInputStream(f)
val cnt = param.available
val bytes = Array.ofDim[Byte](cnt)
println(param.read(bytes)==0xFFd8FFe0)
Sebastian S
  • 4,420
  • 4
  • 34
  • 63
  • Check for a good solution here: https://stackoverflow.com/questions/9643228/test-if-a-file-is-an-image-file – storaged Sep 14 '18 at 11:22
  • You are checking the result of the `read` call, not the data that was read. But I already gave you code for this in my answer to your previous question, so please don't keep asking the same question. – Tim Sep 14 '18 at 11:33
  • i want to do it using without BufferedInputStream and DataInputStream,only FileInputStream –  Sep 14 '18 at 11:37

1 Answers1

1

If you really don't want to use the convenience of DataInputStream.readInt, then here is how you can check the first 4 bytes in Java:

InputStream stream = new FileInputStream("example.jpg");
byte[] bytes = new byte[4];
stream.read(bytes);
byte[] expectedBytes = { (byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0 };
System.out.println(Arrays.equals(expectedBytes, bytes));

and the same in Scala:

val stream = new FileInputStream("example.jpg")
val bytes = Array.ofDim[Byte](4)
stream.read(bytes)
val expectedBytes = Array(0xFF.toByte, 0xD8.toByte, 0xFF.toByte, 0xE0.toByte)
println(Arrays.==(expectedBytes, bytes)) 
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49