简体   繁体   中英

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

i'm trying to develop a REST service, and i managed to return all the data which i need. but I want to create a temporary filder and add some files inside it and put all these objects(folder with its files) in zip file, and when the REST service is called the zip file will be downloaded. here's the code:

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;

    }
}

For this purpose you can directly create folder, add files and zip it on file system. Then you can use HttpServletResponse OutputStream. In this way all for your file processing would be done and you can simple load zip file in HttpServletResponse OutputStream and finally delete all the processing files from file system and give user stream for download

Example :

`@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();
}

`

You can create temporary folder by Files.createTempDirectory(prefix, FileAttribute[] attrs); Then with ZipOutputStream create zip file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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