判断文件类型

package net;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;

public class T {

	public static void loadPNG() throws IOException {
		// Thread.currentThread().getContextClassLoader().getResourceAsStream("banner_live.png");
		String path = T.class.getResource("banner_live.png").getFile();
		File file = new File(path);

		RandomAccessFile pngFile = null;
		FileChannel channel = null;
		try {
			// Read head 8 byte
			ByteBuffer dst = ByteBuffer.allocate(8);
			pngFile = new RandomAccessFile(file, "r");
			channel = pngFile.getChannel();
			channel.read(dst);

			byte[] bytes = dst.array();
			for (byte by : bytes) {
				int a = 0x000000ff & by;
				System.err.print(Integer.toHexString(a));
				System.err.print(" ");
			}
		} finally {
			channel.close();
			pngFile.close();
		}

	}

	public static void loadPNGEx() throws IOException {
		String path = T.class.getResource("banner_live.png").getFile();
		File file = new File(path);

		RandomAccessFile pngFile = null;
		FileChannel fc = null;

		try {
			// 128MB
			pngFile = new RandomAccessFile(file, "rw");
			fc = pngFile.getChannel();
			MappedByteBuffer buffer = fc.map(MapMode.READ_ONLY, 0, 8);

			byte[] arr = null;
			if (buffer.hasArray()) {
				arr = buffer.array();
				System.err.println(arr.toString());
			}

			while (buffer.hasRemaining()) {
				int a = 0x000000ff & buffer.get();
				System.err.print(" " + Integer.toHexString(a));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			fc.close();
			pngFile.close();
		}

	}

	public void testCase1() {
		final Charset charset = Charset.forName("UTF8");
		byte[] array = new byte[1024];
		ByteBuffer buffer = ByteBuffer.wrap(array);
		String str = charset.decode(buffer).toString();
		System.err.println(str);
	}

	public void testCase2() {
		int x = 0xa0;
		System.err.println(x);
		System.err.println(0x0a);
		System.err.println(Integer.toHexString(6894));

		int y = 0x1aee;
		System.err.println(y);
		System.err.println(Integer.toBinaryString(6894));

		System.err.println("--");
		System.err.println(Integer.toString(33, 32));
		Math.pow(2, 3);
	}

	public static void main(String[] args) throws Exception {
		loadPNGEx();
	}
}

enum FileType {
	PNG("1"), GIF("2"), JPEG("3"), BMP("4"), RAR("5");
	private final String type;

	private FileType(String type) {
		this.type = type;
	}

	public String getT() {
		return type;
	}
}

你可能感兴趣的:(文件)