How to get the mime type of a file in Java

To get the mime type of a file in Java you can use the following snippet.

Sample Java

String fileName = "/path/to/file.zip";
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String mimeType = mimeTypesMap.getContentType(fileName);
File file = new File(fileName);
mimeType = mimeTypesMap.getContentType(file);
System.out.println(mimeType);

How to check if number is a prime in Java

To check if number is a prime in Java you can use the following snippet.

Sample Java

public static boolean IsPrime(long input) {
	boolean primeCheck = true;
	for (long count = 3; count <= Math.sqrt(input); count += 2)
		if (input % count == 0) {
			primeCheck = false;
			break;
		}
	if (( input%2 !=0 && primeCheck && input > 2) || input == 2) {
		return true;
	} else {
		return false;
	}
}

How to read a file into a bytearray in Java

To read a file into a bytearray in Java you can use the following snippet.

Sample Java

public static byte[] ReadFileIntoByteArray(File fileName) throws IOException {
    InputStream inputStream = new FileInputStream(fileName);
    byte[] bytes;
        
    try {
        long fileLength = fileName.length();
        if (fileLength > Integer.MAX_VALUE) {
            bytes = new byte[(int)fileLength];
			int readOffset = 0;
			int readCount = 0;
			while ((readCount=inputStream.read(bytes, readOffset, bytes.length-readOffset)) >= 0 && readOffset < bytes.length ) {
				readOffset += readCount;
			}
			if (bytes.length > readOffset) {
				throw new IOException("Could not completely read file " + fileName.getName());
			}
        }
		else{
			throw new IOException("File " + fileName.getName() + " too large (>2GB)!");
		}
    }
    finally {
        inputStream.close();
    }
    return bytes;
}