簡體   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