Java:一些功能代码段

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013066292/article/details/80450965

文件

关于文件

文件转换成byte[]

 private byte[] getBytes(String name) {
        byte[] fileBytes = null
        try {
            RandomAccessFile f = new RandomAccessFile(name, "r")
            fileBytes = new byte[(int) f.length()]
            f.readFully(fileBytes)
        } catch (FileNotFoundException e) {
            e.printStackTrace()
        } catch (IOException e) {
            e.printStackTrace()
        }
        return fileBytes
    }

关于图片

图片文件转成byte[]后如何获取格式

byte[] picture = new byte[30];//假设这是图片
ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(picture));

Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
while (readers.hasNext()) {
    ImageReader read = readers.next();
    System.out.println("format name = " + read.getFormatName());
}

图片文件转成byte[]后如何获取尺寸,类型属性

byte[] picture = new byte[30];
InputStream in = new ByteArrayInputStream(picture);
BufferedImage buf = ImageIO.read(in);
ColorModel model = buf.getColorModel();
int height = buf.getHeight();

数据

随机数

在Java 1.7前,生成指定范围的随机数的标准方法是:

 int randomNum = new Random().nextInt((max - min) + 1) + min;

在1.7后的标准方法是:

int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

InputStream转为byte[]

private byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            baos.write(data, 0, nRead);
        }

        baos.flush();

        return baos.toByteArray();
    }

猜你喜欢

转载自blog.csdn.net/u013066292/article/details/80450965