用SAX读写XML文件
今天的项目里做了一个缓存文件 利用的就是xml
读都好说 其实写也很简单 机械化了一点 不过都是必要的
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.OutputStream;import java.io.StringReader;import java.io.StringWriter;import java.util.ArrayList;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.DefaultHandler;import org.xmlpull.v1.XmlSerializer;import android.util.Xml;import com.yolove.player.entity.AudioInfo;public class PlaylistSyncUtil {public static ArrayList<AudioInfo> list;public PlaylistSyncUtil(){}public static void savetoLocal(ArrayList<AudioInfo> audiolist,String path){//取得文件名String name=path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."));//得到xml序列化工具XmlSerializer serializer=Xml.newSerializer();//生成Stringwriter对象StringWriter writer=new StringWriter();if(audiolist.size()>0){try {serializer.setOutput(writer);//XML文件头serializer.startDocument("UTF-8", true);/* * 开始xml文件主体的构建 * xml的根root为playlist * 次级根为audioInfo 标识每一个单独的audioinfo对象 * 对象中的属性以<></>的格式进行存储 *///<playlist>serializer.startTag("", "playlist");for(int i=0;i<audiolist.size();i++){AudioInfo info=audiolist.get(i);serializer.startTag("", "AudioInfo");serializer.startTag("", "id");serializer.text(info.getId()+"");serializer.endTag("", "id");serializer.startTag("", "data");serializer.text(info.getData()+"");serializer.endTag("", "data");serializer.startTag("", "displayname");serializer.text(info.getDisplayName()+"");serializer.endTag("", "displayname");serializer.startTag("", "size");serializer.text(info.getSize()+"");serializer.endTag("", "size");serializer.startTag("", "dateAdded");serializer.text(info.getDateAdded()+"");serializer.endTag("", "dateAdded");serializer.startTag("", "dateModified");serializer.text(info.getDateModified()+"");serializer.endTag("", "dateModified");serializer.startTag("", "title");serializer.text(info.getTitle()+"");serializer.endTag("", "title");serializer.startTag("", "duration");serializer.text(info.getDuration()+"");serializer.endTag("", "duration");serializer.startTag("", "artistId");serializer.text(info.getArtistId()+"");serializer.endTag("", "artistId");serializer.startTag("", "albumId");serializer.text(info.getAlbumId()+"");serializer.endTag("", "albumId");serializer.startTag("", "year");serializer.text(info.getYear()+"");serializer.endTag("", "year");serializer.startTag("", "bookmark");serializer.text(info.getBookMark()+"");serializer.endTag("", "bookmark");serializer.startTag("", "lrcData");serializer.text(info.getLrcData()+"");serializer.endTag("", "lrcData");serializer.startTag("", "picData");serializer.text(info.getPicData()+"");serializer.endTag("", "picData");serializer.startTag("", "album");serializer.text(info.getAlbum()+"");serializer.endTag("", "album");serializer.startTag("", "artist");serializer.text(info.getArtist()+"");serializer.endTag("", "artist");serializer.startTag("", "lpDownOnce");serializer.text(info.isLpDownOnce()+"");serializer.endTag("", "lpDownOnce");serializer.startTag("", "uuid");serializer.text(info.getUuid()+"");serializer.endTag("", "uuid");serializer.startTag("", "type");serializer.text(info.getType()+"");serializer.endTag("", "type");serializer.startTag("", "smallpicurl");serializer.text(info.getSmallpicurl()+"");serializer.endTag("", "smallpicurl");serializer.startTag("", "bigpicurl");serializer.text(info.getBigpicurl()+"");serializer.endTag("", "bigpicurl");serializer.startTag("", "description");serializer.text(info.getDescription()+"");serializer.endTag("", "description");serializer.startTag("", "isplaying");serializer.text(info.isPlaying()+"");serializer.endTag("", "isplaying");serializer.startTag("", "isselected");serializer.text(info.isSelected()+"");serializer.endTag("", "isselected");serializer.endTag("", "AudioInfo");}serializer.endTag("", "playlist");serializer.endDocument();}catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//结果字符串//writer.toString(); boolean flag = true; BufferedReader bufferedReader = null; BufferedWriter bufferedWriter = null; try { File distFile = new File(path); if(distFile.exists()){ distFile.delete(); } bufferedReader = new BufferedReader(new StringReader(writer.toString())); bufferedWriter = new BufferedWriter(new FileWriter(distFile)); char buf[] = new char[1024]; //字符缓冲区 int len; while ((len = bufferedReader.read(buf)) != -1) { bufferedWriter.write(buf, 0, len); } bufferedWriter.flush(); bufferedReader.close(); bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); flag = false; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }public static ArrayList<AudioInfo> getAudioListFromLocal(String path){SAXParserFactory sax=SAXParserFactory.newInstance();PlaylistXMLHandler playlistHandler=new PlaylistXMLHandler();try {SAXParser parser=sax.newSAXParser();XMLReader reader=parser.getXMLReader();reader.setContentHandler(playlistHandler);reader.parse(new InputSource(new FileInputStream(new File(path))));} catch (ParserConfigurationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SAXException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return list;}static class PlaylistXMLHandler extends DefaultHandler {String tag;AudioInfo info;StringBuilder builder=new StringBuilder();@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {// TODO Auto-generated method stubif(!(tag.equals(""))){builder.append(ch,start,length);}super.characters(ch, start, length);}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {// TODO Auto-generated method stubsuper.endElement(uri, localName, qName);if(tag.equals("uuid")){info.setUuid(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("artist")){info.setArtist(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("id")){info.setId(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("size")){info.setSize(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("bookmark")){info.setBookMark(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}//else if(tag.equals("year")){info.setYear(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("albumId")){info.setAlbumId(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("artistId")){info.setArtistId(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("dateAdded")){info.setDateAdded(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("dateModified")){info.setDateModified(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("title")){info.setTitle(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("lpDownOnce")){info.setLpDownOnce((builder.toString().replaceAll("\n", "").replaceAll("\\s", "").equals("true")?true:false));builder.setLength(0);}else if(tag.equals("isplaying")){info.setPlaying((builder.toString().replaceAll("\n", "").replaceAll("\\s", "").equals("true")?true:false));builder.setLength(0);}else if(tag.equals("isselected")){info.setSelected((builder.toString().replaceAll("\n", "").replaceAll("\\s", "").equals("true")?true:false));builder.setLength(0);}else if(tag.equals("artist")){info.setArtist(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("songname")){info.setTitle(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("album")){info.setAlbum(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("duration")){info.setDuration(Integer.parseInt(builder.toString().replaceAll("\n", "").replaceAll("\\s", "")));builder.setLength(0);}else if(tag.equals("type")){info.setType(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("data")){info.setData(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));//System.out.println("url--->"+builder);builder.setLength(0);}else if(tag.equals("smallpicurl")){info.setSmallpicurl(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));//System.out.println("smallpicurl--->"+builder);builder.setLength(0);}else if(tag.equals("bigpicurl")){info.setBigpicurl(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));//System.out.println("bigpicurl--->"+builder);builder.setLength(0);}else if(tag.equals("lrcData")){info.setLrcData(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("picData")){info.setPicData(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("description")){info.setDescription(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}else if(tag.equals("displayname")){info.setDisplayName(builder.toString().replaceAll("\n", "").replaceAll("\\s", ""));builder.setLength(0);}tag="";if(localName.equals("AudioInfo")){list.add(info);}}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {// TODO Auto-generated method stubsuper.startElement(uri, localName, qName, attributes);tag=localName;if(tag.equals("playlist")){if(list==null)list=new ArrayList<AudioInfo>();else{list.clear();}}else if(tag.equals("AudioInfo")){info=new AudioInfo();}}}}