关于IO流读取文件(xml;java)

来源:互联网 发布:电视型号推荐知乎 编辑:程序博客网 时间:2024/04/29 19:57
递归要有条件 否则会产生内存溢出
http://www.blogjava.net/biiau/archive/2008/09/24/231005.html

显示所有目录以及目录下的文件:
import java.io.*;
class  ListAllFile
{
public static void main(String[] args) throws IOException
{
File dir=new File("e:\\day17");
 listAll(dir);
}
public static void listAll(File dir)
{
System.out.println("dir:"+dir.getName());
File[] files=dir.listFiles();


for (int x=0;x<files.length ;x++ )
{
if(files[x].isDirectory())
{
listAll(files[x]);
}
else
System.out.println("---file"+files[x].getName());
}
}
二、
因为显示的方式不易查看所以要优化结构
用空格来显示目录的等级
import java.io.*;
class  ListAllFile
{
public static void main(String[] args) throws IOException
{
File dir=new File("e:\\day17");
 listAll(dir,0);
}
public static void listAll(File dir,int level)
{
System.out.println(getSpace(level)+dir.getName());

File[] files=dir.listFiles();
level++;
for (int x=0;x<files.length ;x++ )
{
if(files[x].isDirectory())
{
listAll(files[x],level);
}
else
System.out.println(getSpace(level)+files[x].getName());
}
}
private static String getSpace(int level)
{
StringBuffer sb=new StringBuffer();
for (int x=0;x<level ;x++ )
{
sb.append("  ");
}
return sb.toString();
}
}


}
/*
删除一个待内容的目录原理。从最里层往外删除。




*/
public static void delFile(File dir)
{
File[] files = dir.listFiles();
for(int x=0; x<files.length; x++)
{
if(files[x].isDirectory())
delFile(files[x]);
else
System.out.println(files[x].toString()+"......file......"+files[x].delete());
}
System.out.println(dir.toString()+"......dir....."+dir.delete());
}
}




//建立java文件列表。
1,对指定目录进行遍历,需要包括子目录。
2,对遍历到的文件进行判断,
3,将随需文件的绝对路径存入到文本文件中。


import java.io.*;
class  JavaFileList
{
public static void main(String[] args) throws IOException
{
File dir = new File("f:\\java38");
BufferedWriter bufw = new BufferedWriter(new FileWriter("javalist.txt"));
//为了保证流的唯一性,将其变成变量传入方法中
fileList(dir,bufw);
bufw.close();


}



public static void fileList(File dir,BufferedWriter bufw)throws IOException
{
File[] files = dir.listFiles();
for(int x=0; x<files.length; x++)
{
if(files[x].isDirectory())
fileList(files[x],bufw);
else
{
if(files[x].getName().endsWith(".java"))
{//因为file成为了对象所以需要先得到名字在比较
bufw.write(files[x].getAbsolutePath());
bufw.newLine();
bufw.flush();//因为需要循环写入所以不需要关闭
}
}
}
}


}

------------------------------------------------------------------------------------------------------------

IO用来处理设备之间的数据传输,java对数据的操作是通过流的方式,java用于操作流的对象都在io包中
【分类】
按着操作对象分:字节流和字符流
(字符流的出现是因为编码转换的需要)(当处理文字的时候使用字符流)


按流向分:输入流(读) 输出流(写)
按功能的不同:节点流    处理流


  字节流 字符流
输入流  InputStream Reader


输出流   OutputStream Writer
一个字节是八位  字符是两个字节 


字节流 的抽象基类:InputStream OutputStream
字符流 的抽象基类:Reader Writer
【注意】由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀。
例如:InputStream的子类FileInputStream
Reader的子类是FileReader
----------------------------------------------------
字符流:
【第一步】:
FileWriter fw=new FileWriter("test.txt");会抛出一个异常
首先在堆内存中创建了一个对象,同时产生了流调用了底层资源创建了一个文件
()
为什么没有空的构造参数:因为我们在建立对象的时候就必须要初始化。该写入对象一建立就要有目的地。
FileWriter fw=new FileWriter("c:\\test.txt");
注意是双斜杠。一个反斜杠是转移字符。
【第二步】:
fw.write("abcd");
是把数据写到流当中,如果输入新内容会覆盖旧内容
【第三步】
fw.flush();将内存流当中的数据写到目的地当中
或者
fw.close();刷新并关闭资源


flush和close的区别:close关闭了流,flush之后可以继续write


这几个方法都会抛出IOException异常


先在外面建议要使用的流对象,因为try catch的代码块的独立的所以不能创建到内部。在关闭的时候要先判断是否为空,操作几个文件就判断几次,将各个文件的关闭动作独立开,不能一次性关闭
io处理异常写法:
  FileWriter fw=null;
  try
{  fw=new FileWriter("test.txt");
fw.write("abcd");
   }
catch (IOException e)
{
System.out.println(e.toString()+"..");
}
finally
{
if(fw!=null) //为了避免没有文件的时候空指针异常
try
{
fw.close();//也会抛出异常所以try
}
catch (IOException e)
{System.out.println(e.toString()+"......");
}

}


【续写】续写文件的时候,在文件后面加上true
fw = new FileWriter("test.txt",true);
fw.write("aaaaa");
-------------------------------------------------------
【FileRead】
两种格式
一种(定义一个接收数组,接收read返回的数字,然后将它们转成字符串)read(arr)将 将字符读入数组
(字符数组转成字符串,newString(arr))
class  FileReaderDemo
{
public static void main(String[] args) 
{
FileReader fr=new FileReader("text.txt");


char [] arr= new char[1024];
int num=0;
while((num=fr.read(arr))!=-1)
{
system.out.println(new String (arr,0,num));
}
 
}
}  
定义一个StringBuffer的缓冲区
(read方法是读取回车和空格的将其存储到StringBuffer中即可)
import java.lang.*;
import java.io.*;
class  filewriter
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("Demo.java"); 
int ch=0;
String s=null;
 StringBuffer sb=new StringBuffer();
while ((ch=fr.read( ))!=-1)

sb.append((char)ch);
 s=sb.toString();   
}
System.out.println(s);
}
}
第二种:一个字符一个字符的打印
class  FileReaderDemo
{
public static void main(String[] args) 
{
FileReader fr=new FileReader("text.txt"); 
int num=0;
while((num=fr.read())!=-1)
{
system.out.println((char)num);
}
 
}
}  


【BufferedWriter】缓冲区并没有使用底层资源,使用的是流
并没有空的构造函数,在构造的时候就必须有流存在。
public static void main(String[] args) throws Exception
{
FileWriter fw=new FileWriter("text.txt");
BufferedWriter bw=new BufferedWriter(fw);
bw.write("adf");
bw.newLine();//换行 (跨平台)
bw.close();
}
首先要建立写的流,再创建缓冲区,一创建就要具有流所以将创建的流传如缓冲区。


【BufferedReader】
BufferRead中的close方法是不刷新的!!
方法中readLine每次循环都指向下一个对象。line=bufr.readLine()方法必须写在while循环内。而不能写在外面否则就是死循环。


-----一次读取一行
import java.io.*;
class  BufferReaderDemo
{
public static void main(String[] args) 抛出异常
{
BufferedReader bufr=
new BufferedReader(new FileReader("text.txt"));
String line=bufr.readLine();
System.out.println(line);
bufr.close();
}
}
-----循环、定义一个字符串的变量 String=null;
import java.io.*;
class  BufferReaderDemo
{
public static void main(String[] args) 
{
BufferedReader bufr=
new BufferedReader(new FileReader("text.txt"));


String line=null;
while((line=bufr.readLine())!=null)
{
System.out.println(line);
}
bufr.close();
}
}
注意:readLine()不读取回车符,只读取回车符前面的字符。
原理:是使用read()一次读一个的原理,而read ()读取
每一个字符包括回车和换行。


只用BufferedReader和BufferedWriter实现文件的copy
import java.io.*;
class  BufferReaderDemo
{
public static void main(String[] args) throws IOException
{
BufferedReader bufr=
new BufferedReader(new FileReader("text.txt"));
BufferedWriter bwf=
new BufferedWriter(new FileWriter("d:\\text1.txt"));


String line=null;
while((line=bufr.readLine())!=null)
{
bwf.write(line);
bwf.flush();
}
bufr.close();
bufw.close();
}
}

------------------------------------------------------------------------------------------------------------

package com.huawei.test;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;


import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class CopyOfCopy {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
        try {
            XMLWriter writer = null;// 声明写XML的对象
            SAXReader reader = new SAXReader();


            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");// 设置XML文件的编码格式


            String filePath = "F:\\A.xml";
            String filePath2 = "F:\\B.xml";
            String abc = null;
            File file = new File(filePath);
            if (file.exists()) {
                Document document = reader.read(file);// 读取XML文件
                Element root = document.getRootElement();// 得到根节点
                boolean bl = false;
                for (Iterator i = root.elementIterator("string"); i.hasNext();) {
                    Element student = (Element) i.next();
                    if (student.attributeValue("name").equals("second")) {
                        // 修改学生sid=001的学生信息
//                        student.selectSingleNode("姓名").setText("王五");
//                        student.selectSingleNode("年龄").setText("25");


//                        writer = new XMLWriter(new FileWriter(filePath2), format);
//                        writer.write(document);
//                        writer.close();
                    abc=student.getText();
                    System.out.println(abc);
                        bl = true;
                        break;
                    }
                }
                if (bl) {
                    // 添加一个学生信息
                    Element student = root.addElement("string");
                    student.addAttribute("name", "second");
//                    Element sid = student.addElement("编号");
//                    sid.setText("100");
//                    Element name = student.addElement("姓名");
//                    name.setText("嘎嘎");
//                    Element sex = student.addElement("性别");
//                    sex.setText("男");
//                    Element age = student.addElement("年龄");
//                    age.setText("21");
                    student.setText(abc);
                    writer = new XMLWriter(new FileWriter(filePath2), format);
                    writer.write(document);
                    writer.close();
                }
            } else {
//                // 新建student.xml文件并新增内容
//                Document _document = DocumentHelper.createDocument();
//                Element _root = _document.addElement("学生信息");
//                Element _student = _root.addElement("学生");
//                _student.addAttribute("sid", "001");
//                Element _id = _student.addElement("编号");
//                _id.setText("001");
//                Element _name = _student.addElement("姓名");
//                _name.setText("灰机");
//                Element _age = _student.addElement("年龄");
//                _age.setText("18");
//
//                writer = new XMLWriter(new FileWriter(file), format);
//                writer.write(_document);
//                writer.close();
            }
            System.out.println("操作结束! ");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

======================================================================

练习:获取当前行号和数据//设置行号的时候要设置在循环外面
import java.io.*;
class  LineNumberReaderDemo
{
public static void main(String[] args) throws IOException
 {
FileReader fr=new FileReader("text.txt");


LineNumberReader lnr=new LineNumberReader(fr);
String line=null;


         //lnr.setLineNumber(10)从十开始 定义在循环外


while((line=lnr.readLine())!=null)
{
System.out.println(lnr.getLineNumber()+":"+line);
}
lnr.close();
  }
}

原创粉丝点击