繁体   English   中英

如何在Java中创建临时文件夹并在其中添加文件

[英]how to create temporary folder in java and add files inside it

我正在尝试开发REST服务,并且设法返回了我需要的所有数据。 但是我想创建一个临时文件,并在其中添加一些文件,并将所有这些对象(包含文件的文件夹)放入zip文件中,然后在调用REST服务时将下载zip文件。 这是代码:

public class rest {

    private static final String FILE_PATH = "file.xml";

    @GET
    @Path( "/GetSequenceId/{id}" )
    @Consumes( MediaType.APPLICATION_XML )
    @Produces( MediaType.TEXT_XML )
    // @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response showFileStoreDetails( @PathParam( "id" ) String id)
            throws ArchiveException, IOException {

        Response response = null;
        File file = new File( FILE_PATH );
        // String feeds = null;
        Sequence feedData = null;
        Step step = new Step();
        Liststeps listStep = new Liststeps();
        Attachement attachement = new Attachement();
        List<String> listOfAttachement = new ArrayList<String>();
        // List<attachement> listAttachementd = null;
        // File file = new File( "file.xml" );
        // Response response = null;
        // System.out.println( listOfAttachement );
        try {
            /*
             * Database database = new Database(); Connection connection =
             * database.Get_Connection();
             */
            feedData = listStep.getSteps( Integer.parseInt( id ) );
            listOfAttachement = listStep.getAttachementId();
            System.out.println( listOfAttachement );
            System.out.println( "------------Debut---------------------------------------" );
            for ( String att : listOfAttachement ) {
                MongoClient mongoClient = new MongoClient( "localhost", 27017 );
                DB mongoDB = mongoClient.getDB( "tutorial" );

                // Let's store the standard data in regular collection
                DBCollection collection = mongoDB.getCollection( "filestore" );

                /// logger.info( "Inside downloadFilebyID..." );
                // logger.info( "ID: " + id );

                BasicDBObject query = new BasicDBObject();
                query.put( "_id", att );
                // System.out.println( "Mongo_ID :" +
                // att.getIdMongo().toString() );
                DBObject doc = collection.findOne( query );
                DBCursor cursor = collection.find( query );

                if ( cursor.hasNext() ) {

                    Set<String> allKeys = doc.keySet();
                    HashMap<String, String> fields = new HashMap<String, String>();
                    for ( String key : allKeys ) {
                        fields.put( key, doc.get( key ).toString() );
                    }

                    /*
                     * logger.info( "description: " + fields.get( "description"
                     * ) ); logger.info( "department: " + fields.get(
                     * "department" ) ); logger.info( "file_year: " +
                     * fields.get( "file_year" ) );
                     */
                    // logger.info( "filename: " + fields.get( "filename" ) );

                    GridFS fileStore = new GridFS( mongoDB, "filestore" );
                    GridFSDBFile gridFile = fileStore.findOne( query );

                    InputStream in = gridFile.getInputStream();

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    int data = in.read();
                    while ( data >= 0 ) {
                        out.write( (char) data );
                        data = in.read();
                    }
                    out.flush();
                    ResponseBuilder builder = Response.ok( out.toByteArray() );
                    builder.header( "Content-Disposition", "attachment; filename=" + fields.get( "filename" ) );
                    response = builder.build();


                }
            }

            // ProjectManager projectManager = new ProjectManager();

            // feedData = listStep.getSteps( Integer.parseInt( id ) );
            System.out.println( "--------------fin-----------------------------------" );

            // listAttachementd = listStep.getAttachement();
            // StringBuffer sb = new StringBuffer();
            // Gson gson = new Gson();
            // System.out.println( gson.toJson( feedData ) );

            // feeds = gson.toJson( feedData );
            // String xml = org.json.XML.toString(gson);
            // XStream xstream = new XStream();
            // File file = new File( "input.xml" );
            // try {
            //
            // // File file = new File( "input.xml" );
            // JAXBContext jaxbContext = JAXBContext.newInstance( Sequence.class
            // );
            // Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            //
            // // output pretty printed
            // jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT,
            // true );
            //
            // jaxbMarshaller.marshal( feedData, file );
            // jaxbMarshaller.marshal( feedData, System.out );
            //
            // } catch ( JAXBException e ) {
            // e.printStackTrace();
            // }

        } catch ( NumberFormatException e ) {
            System.out.println( e );
        } catch ( Exception e ) {
            e.printStackTrace();
        }

        /*
         * ResponseBuilder response = Response.ok( (Object) file );
         * response.header( "Content-Disposition",
         * "attachment; filename=\"sequence.xml\"" ); System.out.println( file
         * );
         * 
         * return response.build();
         */
        return response;

    }
}

为此,您可以直接创建文件夹,添加文件并将其压缩在文件系统上。 然后,您可以使用HttpServletResponse OutputStream。 这样就可以完成所有文件处理,您可以在HttpServletResponse OutputStream中简单加载zip文件,最后从文件系统中删除所有处理文件,并提供用户流供下载

范例:

`@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
                         @Context HttpServletResponse response) throws IOException {
    try {
        //Get your File or Object from wherever you want...
        //you can use the key parameter to indentify your file
        //otherwise it can be removed
        //let's say your file is called "object"
        response.setContentLength((int) object.getContentLength());
        response.setHeader("Content-Disposition", "attachment; filename="
                + object.getName());
        ServletOutputStream outStream = response.getOutputStream();
        byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
        DataInputStream in = new DataInputStream(
                object.getDataInputStream());
        int length = 0;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            outStream.write(bbuf, 0, length);
        }
        in.close();
        outStream.flush();
    } catch (S3ServiceException e) {
        e.printStackTrace();
    } catch (ServiceException e) {
        e.printStackTrace();
    }
    return Response.ok().build();
}

`

您可以通过Files.createTempDirectory(prefix, FileAttribute[] attrs);创建临时文件夹Files.createTempDirectory(prefix, FileAttribute[] attrs); 然后用ZipOutputStream创建zip文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM