XML file Read and write methods for Android programming _android

Source: Internet
Author: User
Tags server port

This article describes the XML file read and write methods of Android programming. Share to everyone for your reference. The specific analysis is as follows:

First, the environment:

Host: WIN8
Development environment: Eclipse

Second, note:

1. Open the XML file in the SD card, if it does not exist, create a new one and write the default configuration
2. Reading XML files

Three, XML file format:

<?xml version= "1.0" encoding= "UTF-8" standalone= "true"?> 
-<config> 
<title> Remote video interview system </ title> 
<local_port>12600</local_port> 
<schedule_service_ip>10.58.1.59</ schedule_service_ip>
<schedule_service_port>12601</schedule_service_port> 
</config >

Four, the source code:

Package com.example.helloanychat; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.StringWriter; 
Import java.net.Inet6Address; 
Import java.net.InetAddress; 
Import Java.net.NetworkInterface; 
Import java.net.SocketException; 
Import java.util.Enumeration; 
Import Javax.xml.parsers.DocumentBuilder; 
Import Javax.xml.parsers.DocumentBuilderFactory; 
Import android.os.Environment; 
Import Android.util.Log; 
Import org.w3c.dom.Document; 
Import org.w3c.dom.Element; 
Import org.w3c.dom.NodeList; 
Import Org.xmlpull.v1.XmlPullParserFactory; 
Import Org.xmlpull.v1.XmlSerializer; /** * Configuration Information class * New Date: 2014/12/8 by JDH/public class Config implements If_config {//configuration information Private Config_info Co 
 Nfig_info = new Config_info (); 
  /** * Constructor/public Config () {Boolean OK; 
  File Sd_path; 
  File File_cfg_dir; 
  File file_cfg; 
  FileOutputStream out; 
  String str; 
 FileInputStream in; Get the native IP address config_info.local_ip = getlocalipaddress (); 
  System.out.printf ("Local ip:%s\n", CONFIG_INFO.LOCAL_IP); 
  Get SD card Directory Sd_path = Environment.getexternalstoragedirectory ();
  Determine if the folder exists File_cfg_dir = new file (Sd_path.getpath () + "//remote_meeting"); 
   if (!file_cfg_dir.exists () &&!file_cfg_dir.isdirectory ()) {System.out.println ("Configuration folder remote_meeting does not exist!"); 
   OK = File_cfg_dir.mkdirs (); 
   if (OK) {System.out.println ("Create folder succeeded!");      
   else {System.out.println ("Create folder failed!");
  }//Determine if the configuration file exists file_cfg = new file (File_cfg_dir.getpath (), "Cfg.xml");
   if (!file_cfg.exists ()) {System.out.println ("config file cfg.xml does not exist!"); 
    try {file_cfg.createnewfile ();
    System.out.println ("Create File Cfg.xml successful!");
     Generate initialized configuration data try {out = new FileOutputStream (FILE_CFG);
     Save default configuration Config_info.title = "Remote video interview system"; 
     Config_info.local_port = 12600;
     CONFIG_INFO.SCHEDULE_SERVER_IP = "10.58.1.59"; Config_info. Schedule_server_port = 12601;
     str = produce_xml_string (config_info); 
     Out.write (Str.getbytes ()); 
    Out.close (); 
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
   The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
  } config_info.title = "remote"; 
  Config_info.local_port = 126;
  CONFIG_INFO.SCHEDULE_SERVER_IP = "10.5";
  Config_info.schedule_server_port = 12; System.out.printf ("----222222222%s,%d,%s,%d\n", Config_info.title,config_info.local_port, Config_info.schedule_
  Server_ip,config_info.schedule_server_port);
   Parse XML file try {in = new FileInputStream (FILE_CFG); 
   Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
   Documentbuilder builder = Factory.newdocumentbuilder ();
   Document document = Builder.parse (in);
   Gets the root node Element root = Document.getdocumentelement (); 
   NodeList node = root.getchildnodes (); 
 Get 1th child node: Title  Config_info.title = Node.item (0). Getfirstchild (). Getnodevalue ();
   Get 2nd child node: Native Port Config_info.local_port = Integer.parseint (Node.item (1). Getfirstchild (). Getnodevalue ()); 
   Get 3rd child node: Dispatch server IP config_info.schedule_server_ip = Node.item (2). Getfirstchild (). Getnodevalue (); Get 4th child node: Dispatch server Port Config_info.schedule_server_port = Integer.parseint (Node.item (3). Getfirstchild (). Getnodevalue ()  
   ); System.out.printf ("----222222222%s,%d,%s,%d\n", Config_info.title,config_info.local_port, Config_info.schedule_ 
  Server_ip,config_info.schedule_server_port); 
  catch (Exception e) {e.printstacktrace (); 
 @Override public Config_info Get_config_info () {return config_info; /** * Get native IP address * @return native IP address/private String getlocalipaddress () {try {for Enumeration<ne Tworkinterface> en = networkinterface. getnetworkinterfaces (); En.hasmoreelements ();) 
    {NetworkInterface intf = en.nextelement (); for (enumeration<inetaddress> enumipaddr = intf. getinetaddresses (); Enumipaddr.hasmoreelements ();) 
     {InetAddress inetaddress = enumipaddr.nextelement (); if (!inetaddress.isloopbackaddress ()) {if (!inetaddress.isloopbackaddress () &&! ( 
     InetAddress instanceof inet6address)) {return inetaddress.gethostaddress (). toString (); 
  catch (SocketException ex) {LOG.E ("wifipreference IPAddress", ex.tostring ()); 
 return null; /** * Generate XML configuration file string data stream * Config_info native IP information does not save * @param info: Configuration information * @return XML string Data flow * * PRIV 
  Ate String produce_xml_string (Config_info Info) {StringWriter StringWriter = new StringWriter (); 
   try {//Get XmlSerializer object Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance (); 
   XmlSerializer XmlSerializer = Factory.newserializer (); 
   Set the output Stream object Xmlserializer.setoutput (StringWriter); 
   Start tag xmlserializer.startdocument ("Utf-8", true); XmlserIalizer.starttag (null, "config"); 
   Title Xmlserializer.starttag (null, "title"); 
   Xmlserializer.text (Info.title); 
   Xmlserializer.endtag (null, "title"); 
   Native port Xmlserializer.starttag (null, "Local_port"); 
   Xmlserializer.text (integer.tostring (Info.local_port)); 
   Xmlserializer.endtag (NULL, "Local_port"); 
   Dispatch server IP xmlserializer.starttag (null, "schedule_service_ip"); 
   Xmlserializer.text (INFO.SCHEDULE_SERVER_IP); 
   Xmlserializer.endtag (NULL, "schedule_service_ip"); 
   Dispatch server port Xmlserializer.starttag (null, "Schedule_service_port"); 
   Xmlserializer.text (integer.tostring (Info.schedule_server_port)); 
   Xmlserializer.endtag (NULL, "Schedule_service_port"); 
   Xmlserializer.endtag (null, "config"); 
  Xmlserializer.enddocument (); 
  catch (Exception e) {e.printstacktrace (); 
 return stringwriter.tostring (); } 
}

I hope this article will help you with your Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.