本文主要是介绍Java:一些功能代码段,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文件
关于文件
文件转换成byte[]
private byte[] getBytes(String name) {byte[] fileBytes = nulltry {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();}
这篇关于Java:一些功能代码段的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!