生成100000以内的素数XML文件的Demo(Jdom写成)

来源:互联网 发布:淘宝手机端怎么做推广 编辑:程序博客网 时间:2024/05/01 01:34
</pre><pre name="code" class="java">
<pre name="code" class="java">public class TestPrimeXml {private static String fileName = "Primes.xml";//获取源文件路径private static String path = System.getProperty("user.dir") + File.separator + "src" + File.separator + fileName;public static void main(String[] args) {//创建PrimeXML文档creatPrimeXML(100000);//输入一个数字,检验是否为质数,如果是则返回相应的下标位置,如果不是则打印其为合数checkNum(73897);Add();}//添加一些片段private static void Add() {try {//创建解析器SAXBuilder sb = new SAXBuilder();//获取要解析的目标文件File file = new File(path);//解析文件获取documentDocument document = sb.build(file);Element rooteElement = document.getRootElement();//获取子节点集合List<Element> eList = rooteElement.getChildren();for (Element element : eList) {element.setAttribute("name", "wanglf");}rooteElement.setAttribute("name", "wanglf");saveDocument(document);} catch (Exception e) {e.printStackTrace();}}@SuppressWarnings("unchecked")private static void checkNum(int i) {if (!isPrimeBaidu(i)) {System.out.println(i + "是合数");} else {try {//创建解析器SAXBuilder sb = new SAXBuilder();//获取要解析的目标文件File file = new File(path);//解析文件获取documentDocument document = sb.build(file);//获取文档根节点Element rootElement = document.getRootElement();//获取指定节点的所有子节点List<Element> eList = rootElement.getChildren();for (Element element : eList) {if (element.getText().equals(i + "")) {System.out.println(i + "所在的id为:" + element.getAttributeValue("id"));System.exit(0);}}} catch (Exception e) {e.printStackTrace();}}}public static void creatPrimeXML(Integer s) {try {long f1 = System.nanoTime();Document document = getDocument(s);saveDocument(document);long f2 = System.nanoTime();//计算运行时间System.out.println("总共用时" + (f2 - f1) / 10e8 + "秒");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}private static void saveDocument(Document document) throws Exception{//格式化Format format = Format.getPrettyFormat();//输出文本XMLOutputter out = new XMLOutputter(format);out.output(document, new FileOutputStream(path));}/** *  * @param n * @return Document */private static Document getDocument(Integer n) {Element rootElement = new Element("primes");int s = 1;for (int i = 2; i <= n; i++) {if (isPrimeBaidu(i)) {Element element = new Element("prime");element.setAttribute("id", s + "");element.setText(i + "");rootElement.addContent(element);s++;}}Document document = new Document(rootElement);return document;}/** * 一个很优秀的素数计算方法 * @param n * @return boolean */public static boolean isPrimeBaidu(long n) {if (n <= 3) {return n > 1;} else if (n % 2 == 0 || n % 3 == 0) {return false;} else {for (int i = 5; i * i <= n; i += 6) {if (n % i == 0 || n % (i + 2) == 0) {return false;}}return true;}}}


                                             
0 0
原创粉丝点击