【问题标题】:how to create temporary folder in java and add files inside it如何在java中创建临时文件夹并在其中添加文件
【发布时间】:2016-03-11 22:52:21
【问题描述】:

我正在尝试开发 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;

    }
}

【问题讨论】:

    标签: java file rest zip directory


    【解决方案1】:

    为此,您可以直接创建文件夹,添加文件并将其压缩到文件系统上。然后你可以使用 HttpServletResponse 输出流。这样你的文件处理就完成了,你可以简单地在 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();
    }
    

    `

    【讨论】:

    • 感谢您的回答,但我如何压缩所有文件,压缩文件必须动态创建
    • 查看动态创建它是不可能的,因为要创建这个场景,您必须:创建一个文件夹,然后向其中添加文件,然后压缩它,您必须传递文件夹路径。因此,我建议您通过将时间戳附加到其名称并处理它来使用一个常见的位置创建文件夹。它也将避免并发请求的重复。对于这种情况,我已经实现了相同的自我。
    • 我有一个列表作为对象
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-11
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      相关资源
      最近更新 更多