Java 编辑文件

filePathName="D:\\Eclipse\\FileReader\\text2.txt";

 

1. 判断文件是否存在

File f=new File(filePathName)

f.exists(); //返回值是boolean

 

2. 创建文件

FileWriter fw =new FileWriter(filePathName);

 

3. 读txt文件

public String readTxtFile() throws Exception {
  int a =0;
  String b="";
  try{FileReader fr=new FileReader(filePathName);
  while((a=fr.read())!=-1)
  {
      b=b+String.valueOf((char)a);
  }
  }
  catch(Exception e)
  {
   throw e;
  }
  return b;
 }
  
 public String readTxtFilebyLine() throws Exception {
  BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filePathName)));
  String data=in.readLine();
  String b="";
  while(data!=null)
  { 
   b=b+data+"\n";
            data=in.readLine();
  }
  return b;
 }

 

4. 写txt文件

public void writeTxtFile(String inputString) throws Exception {
  FileWriter fw=new FileWriter(filePathName);
  fw.write(inputString, 0, inputString.length());
  fw.flush();
  fw.close(); 
 }

 public void AppendTxtFile(String inputString) throws Exception {
  FileWriter fw=new FileWriter(filePathName, true);
  fw.write(inputString, 0, inputString.length());
  fw.flush();
  fw.close(); 
 }

 

5. 删除文件

File f=new File(filePathName)

f.delete();

 

6. 读写xml文件

在java环境下读取xml文件的方法主要有4种:DOM、SAX、JDOM、JAXB,详细请见http://www.blogjava.net/cyck02/archive/2005/12/03/22336.html
目前尝试了JDOM的方法

 解析一个xml文档,基本可以看成以下几个步骤:

  1.实例化一个合适的解析器对象

  本例中我们使用SAXBuilder:

  SAXBuilder sb = new SAXBuilder();

  2.以包含XML数据的文件为参数,构建一个文档对象myDocument

  Document myDocument = sb.build(/some/directory/myFile.xml);

  3.获到根元素

  Element rootElement = myDocument.getRootElement();

  一旦你获取了根元素,你就可以很方便地对它下面的子元素进行操作了,下面对Element对象的一些常用方法作一下简单说明:

  getChild("childname") 返回指定名字的子节点,如果同一级有多个同名子节点,则只返回第一个;如果没有返回null值。

  getChildren("childname") 返回指定名字的子节点List集合。这样你就可以遍历所有的同一级同名子节点。

  getAttributeValue("name") 返回指定属性名字的值。如果没有该属性则返回null,有该属性但是值为空,则返回空字符串。

  getChildText("childname") 返回指定子节点的内容文本值。

  getText() 返回该元素的内容文本值。

 

public String readXmlFilebyTag(String nodeName) throws Exception {
   try{
   Element root=null;
   int i;
   String nodeValue=null;
      SAXBuilder builder =new SAXBuilder(false);
      Document doc=builder.build(filePathName);
      Namespace ns = Namespace.getNamespace("LIT", "http://www.lit.edu.cn/student/");
      root=doc.getRootElement();
      Logger.getLogger(className).info("XML root is "+root);
      List lst =root.getChildren();
      Logger.getLogger(className).info("XML Child nods is "+lst.size());     
      for (i=0;i< lst.size();i++)
      {
       Element elmt = (Element)lst.get(i);
       if (elmt.getName().equalsIgnoreCase(nodeName))
       {
       nodeValue=elmt.getText();//如果是复杂的xml,有id,name 等属性,可以用getAttributeValue("name")
    Logger.getLogger(className).info("nodeValue is "+nodeValue);
    break;
       }
      }
      if(nodeValue==null)
      {
       throw new Exception("can't find such node");
      }
   }
 catch(Exception e)
 {
  throw e;
 }
 return null;
 }

xml文件如下

<LIT:table xmlns:LIT="http://www.w3school.com.cn/furniture" >
 <LIT:t1>a</LIT:t1>
 <LIT:t2>b</LIT:t2>
 <LIT:t3>c</LIT:t3>
</LIT:table>

 如果XML有很多层级,可以用JDOM+Xpath的方法

JDOM的关于XPATH的api在org.jdom.xpath这个包里。看看这个包下,只有一个类,JDOM就是如此简洁,什么事都不故弄玄虚的搞得那么复杂。这个类中的核心的api主要是两个selectNodes()和selectSingleNode()。前者根据一个xpath语句返回一组节点;后者根据一个xpath语句返回符合条件的第一个节点。

需要下载一个包来支持Xpath

http://blog.csdn.net/hbcui1984/article/details/1270163

下面的程序我们用JDOM+XPATH实现了上一个程序同样的功能,你可以从中学到不少运用XPATH 的知识:

import java.util.*;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class Sample2 {  
 public static void main(String[] args) throws Exception {
  SAXBuilder sb = new SAXBuilder();
  Document doc = sb.build("sample.xml");
  Element root = doc.getRootElement();
  List list = XPath.selectNodes(root, "/HD/disk");
  for (int i = 0; i < list.size(); i++) { 
   Element disk_element = (Element) list.get(i);
   String name = disk_element.getAttributeValue("name");
   String capacity = ( (Text) XPath.selectSingleNode(disk_element, 
    "//disk[@name='" + name + "']/capacity/text()")).getTextNormalize();
   String directories = ( (Text) XPath.selectSingleNode(disk_element,  
    "//disk[@name='" + name + "']/directories/text()")).getTextNormalize();
   String files = ( (Text) XPath.selectSingleNode(disk_element,  
    "//disk[@name='" + name + "']/files/text()")).getTextNormalize();
   System.out.println("磁盘信息:");
   System.out.println("分区盘符:" + name);
   System.out.println("分区容量:" + capacity);
   System.out.println("目录数:" + directories);
   System.out.println("文件数:" + files);
   System.out.println("-----------------------------------");
  }
 }
}
                

7. 编辑XML

http://blog.csdn.net/fakir08/article/details/1660749

1)使用JDOM首先要指定使用什么解析器。如:
      SAXBuilder builder=new SAXBuilder(false); 这表示使用的是默认的解析器
(2)得到Document,我们以后要进行的所有操作都是对这个Document操作的:
      Document doc=builder.build(xmlpath);
(3)得到根元素:
      Element books=doc.getRootElement();
在JDOM中所有的节点(DOM中的概念)都是一个org.jdom.Element类,当然他的子节点也是一个org.jdom.Element类。
(4)得到元素(节点)的集合:
    List booklist=books.getChildren("book");
这表示得到“books”元素的所在名称为“book”的元素,并把这些元素都放到一个List集合中
(5)轮循List集合
    for (Iterator iter = booklist.iterator(); iter.hasNext();) {
    Element book = (Element) iter.next();
  }
还有一种轮循方法是:
  for(int i=0;I<booklist.size();I++){
    Element book=(Element)booklist.get(i);
  }
(6)取得元素的属性:
  String email=book.getAttributeValue("email");
  取得元素book的属性名为“email”的属性值。
(7)取得元素的子元素(为最低层元素)的值:
  String name=book.getChildTextTrim("name");
  注意的是,必须确定book元素的名为“name”的子元素只有一个。
(8)改变元素(为最低层元素)的值:
  book.getChild("name").setText("alterrjzjh");
  这只是对Document的修改,并没有在实际的XML文档中进行修改
(9)保存Document的修改到XML文件中:
  XMLOutputter outputter=new XMLOutputter();
  outputter.output(doc,new FileOutputStream(xmlpath));

refer to:

http://www.ibm.com/developerworks/cn/xml/x-jdom/

 http://baike.baidu.com/view/1569983.htm

http://blog.csdn.net/smartcat86/article/details/4085739/

http://blog.csdn.net/liangrockman/article/details/5777031

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值