⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 svgsaveclose.java

📁 完全基于java开发的svg矢量绘图工具
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                                String uri=selectedFile.toURI().toString();                                                                if(	! uri.endsWith(SVGToolkit.SVG_FILE_EXTENSION) &&                                 	! uri.endsWith(SVGToolkit.SVGZ_FILE_EXTENSION)){                                                                    	uri=uri.concat(SVGToolkit.SVG_FILE_EXTENSION);                                }                                                                try{                                	selectedFile=new File(new URI(uri));                                }catch (Exception ex){}                                if(selectedFile!=null && selectedFile.exists()){                                                                        //if the file exist prompts a dialog to confirm that the file will be erased                                    rVal=JOptionPane.showConfirmDialog( 	SVGEditor.getParent(), 													                                            savecloseerasemessage, 													                                            savecloseerasetitle, 													                                            JOptionPane.YES_NO_OPTION);                                                                        //if the file should be erased                                    if(rVal==JOptionPane.YES_OPTION){                                                                                save(frame, selectedFile);                                        break;                                    }                                                                    }else if(selectedFile!=null){                                                                        //if the file does not already exists                                    save(frame, selectedFile);                                    break;                                }                                                            }else{                                                                //the cancel button from the button chooser has been clicked, therefore,                                 //nothing is done                                allowCloseAction=false;                                                                break;                            }                                                    }while(selectedFile!=null && selectedFile.exists());                                            }else{                                                //if the file has already been saved or has been open before its changes, it saves the file                        save(frame, file);                    }                }                                if(isCloseAction && allowCloseAction) {                                        close(frame);                }            }        });    }        /**     * saves the SVG picture to a SVG file given a URI     * @param frame the related svg frame     * @param newFile the file of the next save action     */    protected void save(SVGFrame frame, File newFile){                if(frame!=null && newFile!=null){                        String newSVGPath=newFile.toURI().toString();                        if(newSVGPath!=null){                                final Document doc=frame.getScrollPane().getSVGCanvas().getDocument();                final String fnewSVGPath=newSVGPath;                                if(doc!=null){                                        try{                        Runnable runnable=new Runnable(){                                                        public void run(){                                                                try{                                	getSVGEditor().getSVGToolkit().removeUselessAttributes(doc.getDocumentElement());                                	printXML(SVGEditor.getParent(), doc, new File(new URI(fnewSVGPath)), fnewSVGPath);                                }catch(Exception ex){}                               }                        };                                                frame.enqueue(runnable);                                            }catch (Exception ex){                                                JOptionPane.showMessageDialog(SVGEditor.getParent(), savewarningmessage, savewarningtitle, JOptionPane.WARNING_MESSAGE);                        return;                    }                                        //refreshes the name of the SVGFrame                    if(frame.getName()!=null && newSVGPath!=null && ! frame.getName().equals(newSVGPath)){                                                getSVGEditor().getFrameManager().changeName(frame.getName(), newSVGPath);                                                //adding the file name to the list of the recent files                        getSVGEditor().getResource().addRecentFile(newSVGPath);                        //re-building the open recent menu                        Object obj=getSVGEditor().getSVGModuleLoader().getModule("NewOpen");                                                if(obj!=null){                                                        try{                                obj.getClass().getMethod("buildOpenRecentMenu", (Class[])null).invoke(obj, (Object[])null);                            }catch (Exception ex){}                        }                    }                                        frame.setModified(false);                }			            }        }    }        /**     * prints the given document into the given file     * @param parentContainer     * @param doc     * @param file     * @param newSVGPath     */    protected void printXML(Container parentContainer, final Document doc, final File file, String newSVGPath){    	        File newPath=null;                if(newSVGPath!=null && ! newSVGPath.equals("")){                        try{                newPath=new File(new URI(newSVGPath));            }catch (Exception ex){}        }        if(newPath!=null){        	            //creating the dialog displaying a progress bar            SVGProgressBarDialog pb=null;                        if(parentContainer instanceof JFrame){            	            	pb=new SVGProgressBarDialog((JFrame)parentContainer, labelsave);            	            }else{            	            	pb=new SVGProgressBarDialog(new JFrame(""), labelsave);            }                        final SVGProgressBarDialog progressBarDialog=pb;            progressBarDialog.setVisible(true);            progressBarDialog.setIndeterminate(false, true);            //getting the number of nodes in the tree            int nodesNumber=0;            for(NodeIterator it=new NodeIterator(doc.getDocumentElement()); it.hasNext();){            	            	it.next();            	nodesNumber++;            }                        progressBarDialog.setMax(nodesNumber);                        Thread thread=new Thread(){            	            	@Override            	public void run() {                    //writing the writer                    try{                    	                    	boolean isSVGFile=file.getName().endsWith(SVGToolkit.SVG_FILE_EXTENSION);                    	                    	//converts the svg document into xml strings                        StringBuffer buffer=new StringBuffer("");                        for (Node node=doc.getFirstChild(); node != null; node=node.getNextSibling()) {                        	                        	writeNode(node, buffer, progressBarDialog, 0, isSVGFile);                        }                    	                		ByteBuffer byteBuffer=ByteBuffer.wrap(buffer.toString().getBytes("UTF-8"));                        FileOutputStream out=new FileOutputStream(file);                                                if(! isSVGFile){                        	                        	//compressing the svg content                        	GZIPOutputStream zout=new GZIPOutputStream(out);                        	                        	zout.write(byteBuffer.array());                        	zout.flush();                        	zout.close();                        	                        }else{                        	                        	//writing the svg content without compression                            FileChannel channel=out.getChannel();                            channel.write(byteBuffer);                            channel.close();                        }                                                out.close();                                            }catch (Exception ex){ex.printStackTrace();}                                        progressBarDialog.setVisible(false);            	}            };                        thread.start();        }    }    /**     * writes the string representation of the given node in the given string buffer     * @param node a node     * @param buffer the string buffer     * @param progressBarDialog the progress bar dialog used to show the save action progress     * @param indent the indent     * @param format whether the xml should be formatted     */    public static void writeNode(Node node, StringBuffer buffer, final SVGProgressBarDialog progressBarDialog,     												int indent, boolean format){    	    	if(node!=null){            switch (node.getNodeType()) {                        case Node.ELEMENT_NODE:            	                buffer.append("<");                buffer.append(node.getNodeName());                if (node.hasAttributes()) {                	                    NamedNodeMap attr = node.getAttributes();                    int len = attr.getLength();                                        for (int i = 0; i < len; i++) {                    	                        Attr a = (Attr)attr.item(i);                        buffer.append(" ");                        buffer.append(a.getNodeName());                        buffer.append("=\"");                        buffer.append(contentToString(a.getNodeValue()));                        buffer.append("\"");                    }                }                Node c = node.getFirstChild();                                if (c != null) {                	                    buffer.append(">");                                        if(format){                    	                    	buffer.append("\n");                    }                                        for (; c != null; c = c.getNextSibling()) {                    	                        writeNode(c, buffer, progressBarDialog, indent+1, format);                    }                    buffer.append("</");                    buffer.append(node.getNodeName());                    buffer.append(">");                                    } else {                	                    buffer.append("/>");                }                                if(format){                	                	buffer.append("\n");                }                                break;                            case Node.TEXT_NODE:            	                buffer.append(contentToString(node.getNodeValue()));                break;                            case Node.CDATA_SECTION_NODE:            	                buffer.append("<![CDATA[");                buffer.append(node.getNodeValue());                buffer.append("]]>");                break;                            case Node.ENTITY_REFERENCE_NODE:            	                buffer.append("&");                buffer.append(node.getNodeName());                buffer.append(";");                break;                            case Node.PROCESSING_INSTRUCTION_NODE:            	                buffer.append("<?");                buffer.append(node.getNodeName());                buffer.append(" ");                buffer.append(node.getNodeValue());                buffer.append("?>");                break;                            case Node.COMMENT_NODE:            	                buffer.append("<!--");                buffer.append(node.getNodeValue());                buffer.append("-->");                break;                            case Node.DOCUMENT_TYPE_NODE:             	                DocumentType dt = (DocumentType)node;                buffer.append ("<!DOCTYPE ");                 buffer.append (node.getOwnerDocument().getDocumentElement().getNodeName());                String pubID = dt.getPublicId();                                if (pubID != null) {                	                    buffer.append (" PUBLIC \"" + dt.getNodeName() + "\" \"" +                               pubID + "\">");                                    } else {                	                    String sysID = dt.getSystemId();                                        if (sysID != null){                    	                        buffer.append (" SYSTEM \"" + sysID + "\">");                    }                }                break;            }                        SwingUtilities.invokeLater(new Runnable(){            	            	public void run() {                    progressBarDialog.incrementProgressBarValue();            	}            });    	}    }        /**     * @param s the string to be modified     * @return the given content value transformed to replace invalid     * characters with entities.     */    public static String contentToString(String s) {    	        StringBuffer result = new StringBuffer();                s=s.replaceAll("\\n+", "");        s=s.replaceAll("\\r+", "");        s=s.replaceAll("\\t+", "");        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            switch (c) {            case '<':                result.append("&lt;");                break;            case '>':                result.append("&gt;");                break;            case '&':                result.append("&amp;");                break;            case '"':                result.append("&quot;");                break;            case '\'':                result.append("&apos;");                break;            default:                result.append(c);            }        }                return result.toString();    }        /**     * closes the current SVG picture     * @param frame a frame     */    public void close(SVGFrame frame){                if(frame!=null){                        getSVGEditor().getFrameManager().removeFrame(frame.getName());        }    }        /**     * gets the module's name     * @return the module's name     */    public String getName(){        return idsaveclose;    }    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -