java常用功能
1.复制文件
private void fileChannelCopy(File source, File target) throws IOException { FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { fi = new FileInputStream(source); fo = new FileOutputStream(target); in = fi.getChannel(); out = fo.getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { fi.close(); in.close(); fo.close(); out.close(); } catch (IOException e) { LOGGER.error("File copy failed.", e); } } }
2. restApi 显示图片
@GET @Path("/") @Produces("image/*")public StreamingOutput getImage(final @QueryParam("path") String path) throws IOException { LOGGER.debug("source:" + path); return new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { try ( InputStream in = storage.getDocument(path)) { output.write(IOUtils.readBytesFromStream(in)); } catch (final FileNotFoundException ex) { LOGGER.error("file is not founded.", ex); throw new NotFoundException(); } } }; }
public class StorageUtil { private final File folder = new File("/macc/img"); public StorageUtil() throws IOException { if (!folder.exists() && !folder.mkdirs()) { throw new IOException("Unable to initialize FS storage:" + folder.getAbsolutePath()); } if (!folder.isDirectory() || !folder.canWrite() || !folder.canRead()) { throw new IOException("Unable to access FS storage:" + folder.getAbsolutePath()); } } public void addDocument(final String name, final byte[] content) throws IOException { try (InputStream in = new ByteArrayInputStream(content)) { addDocument(name, in); } } public void addDocument(final String name, final InputStream in) throws IOException { final File f = new File(folder, name); if (f.exists() && !f.delete()) { throw new IOException("Unable to delete FS file:" + f.getAbsolutePath()); } try (OutputStream out = new BufferedOutputStream(new FileOutputStream(f))) { out.write(IOUtils.readBytesFromStream(in)); f.deleteOnExit(); } } public InputStream getDocument(final String name) throws IOException { String path = folder + "/" + name; final File f = new File(path); if (!f.exists() || !f.isFile()) { throw new FileNotFoundException("Unable to access FS file:" + f.getAbsolutePath()); } return new FileInputStream(f); } public void deleteAll() throws IOException { for (final File f: folder.listFiles()) { if (!f.delete()) { throw new IOException("Unable to delete FS file:" + f.getAbsolutePath()); } } } }
3.上传图片-表单模式
@POST @Consumes("multipart/form-data") @Path("/upload") public Response uploadFileByForm(@Context HttpServletRequest imgRequest, @Multipart(value="name",type="text/plain")String name, @Multipart(value="file")Attachment image) { DataHandler dh = image.getDataHandler(); try { InputStream ins = dh.getInputStream(); writeToFile(ins, "/macc/img/" + dh.getName()); } catch (Exception e) { LOGGER.error("upload failed.", e); } return Response.ok().entity("ok").build(); }
4.图片上传-二进制流模式
@POST @Consumes(MediaType.APPLICATION_OCTET_STREAM) @ModuleSecurityAuth(moduleId=ModuleId.PLAN ,privilegeOperation=PrivilegeOperation.WRITE) @Path("/uploadstream") public UploadFileRsp uploadFile(@Context HttpServletRequest imgRequest) { UploadFileRsp response =new UploadFileRsp(); try { InputStream ins = imgRequest.getInputStream(); Integer groupId = Integer.parseInt(imgRequest.getParameter("group_id")); String name = imgRequest.getParameter("name"); BufferedImage bi =ImageIO.read(ins); int height = bi.getHeight(); int width = bi.getWidth(); String storeName = getStoreName(groupId); String path = tenantId() + "/" + storeName; File out = new File(PLAN_PICTURE_PATH + path); //没有文件夹则创建 if(!out.getParentFile().exists()) out.getParentFile().mkdirs(); ImageIO.write(bi, getSuffix(name), out); pictureService.bindPicture2Floor(path, name, tenantId(), userId(), groupId, width, height); response.setHeight(height); response.setPath(path); response.setWidth(width); } catch (Exception e) { LOGGER.error("upload failed.", e); response.buildCode(RestCode.PICTURE_UPLOAD_ERROR); } return response; }